求助: cin 输入WA 与 getline AC求解
查看原帖
求助: cin 输入WA 与 getline AC求解
704724
raysun007楼主2023/2/8 23:04

求助各位同学解答下cin输入会WA的原因

只有输入不一样,有同学能帮忙解答一下嘛

使用getline() AC

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<set>
#include<unordered_set>
#include<vector>
#include<climits>
#include<limits>
#include<map>
#include<unordered_map>

using namespace std;

void split(const std::string& s, std::vector<std::string>& v, const std::string& c) {
	std::string::size_type pos1, pos2;
	size_t len = s.length();
	pos2 = s.find(c);
	pos1 = 0;
	while (std::string::npos != pos2) {
		v.emplace_back(s.substr(pos1, pos2 - pos1));
 
		pos1 = pos2 + c.size();
		pos2 = s.find(c, pos1);
	}
	if (pos1 != len) {
		v.emplace_back(s.substr(pos1));
  }
}


void toLowerCase(string& s) {
  for (int i = 0; i < s.size(); i++) {
    if (s[i] - 'A' <= 25) {
      s[i] = s[i] + 32;
    }
  }
}


int main() {
  string s;
  getline(cin, s);
  toLowerCase(s);
  
  string str;
  getline(cin, str);
  vector<string> v;
  split(str, v, " ");

  int cnt = 0;
  int pos = 0;
  int sum = 0;
  for (int i = 0; i < v.size(); i++) {
    sum += v[i].size();
    toLowerCase(v[i]);
    if (v[i] == s) {
      cnt++;
      if (cnt == 1) {
        pos = sum - v[i].size() + i;
      }
    }
  }
  
  if (cnt == 0) {
    cout << -1 << endl;
  } else {
    cout << cnt << " " << pos << endl;
  } 
  return 0;
}

使用cin输入 WA

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<set>
#include<unordered_set>
#include<vector>
#include<climits>
#include<limits>
#include<map>
#include<unordered_map>

using namespace std;

void split(const std::string& s, std::vector<std::string>& v, const std::string& c) {
	std::string::size_type pos1, pos2;
	size_t len = s.length();
	pos2 = s.find(c);
	pos1 = 0;
	while (std::string::npos != pos2) {
		v.emplace_back(s.substr(pos1, pos2 - pos1));
 
		pos1 = pos2 + c.size();
		pos2 = s.find(c, pos1);
	}
	if (pos1 != len) {
		v.emplace_back(s.substr(pos1));
  }
}


void toLowerCase(string& s) {
  for (int i = 0; i < s.size(); i++) {
    if (s[i] - 'A' <= 25) {
      s[i] = s[i] + 32;
    }
  }
}


int main() {
  string s;
  // 仅有此处与上述代码不同
  cin >> s;
  toLowerCase(s);
  
  string str;
  getline(cin, str);
  vector<string> v;
  split(str, v, " ");

  int cnt = 0;
  int pos = 0;
  int sum = 0;
  for (int i = 0; i < v.size(); i++) {
    sum += v[i].size();
    toLowerCase(v[i]);
    if (v[i] == s) {
      cnt++;
      if (cnt == 1) {
        pos = sum - v[i].size() + i;
      }
    }
  }
  
  if (cnt == 0) {
    cout << -1 << endl;
  } else {
    cout << cnt << " " << pos << endl;
  } 
  return 0;
}
2023/2/8 23:04
加载中...