CLICK HERE TO SEE THE IMAGE PROBLEM
C++ -我的代码有一个很大的问题,我不知道我在哪里犯了错误,因为我没有得到我想要的结果,例如,第一个输出问题问我:(
Outputs that I'm getting wrong
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName, middleName, lastName, theName;
getline(cin, theName);
int findN = theName.find(" ");
firstName = theName.substr(0, findN);
int findN2 = theName.find(" ", findN + 1);
if (findN2 != string::npos){
middleName = theName.substr(findN2 + 1, findN2 - findN - 1);
lastName = theName.substr(findN2 + 1, theName.length() - findN2 - 1);
cout << lastName << ", " << firstName[0] << "." << middleName[0] << "." << endl;
}
else {
lastName = theName.substr(findN + 1, theName.length() - findN - 1);
cout << lastName << ", " << firstName[0] << " . " << endl;
}
return 0;
}发布于 2020-10-03 08:48:54
我建议学习使用调试器。
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName, middleName, lastName, theName;
getline(cin, theName);
int findN = theName.find(" ");
firstName = theName.substr(0, findN);
int findN2 = theName.find(" ", findN + 1);
if (findN2 != string::npos) {
//changed from findN2 + 1 to findN + 1
middleName = theName.substr(findN + 1, findN2 - findN - 1);
lastName = theName.substr(findN2 + 1, theName.length() - findN2 - 1);
cout << lastName << ", " << firstName[0] << "." << middleName[0] << "." << endl;
}
else {
lastName = theName.substr(findN + 1, theName.length() - findN - 1);
//fixed the white space " . " -> ". "
cout << lastName << ", " << firstName[0] << ". " << endl;
}
return 0;
}发布于 2020-10-03 08:56:03
这很容易用调试器解决。
如果有第二个空格,则会为middleName和middleName分配从findN2 + 1开始的子字符串。
如果没有第二个空格,则在.周围有额外的空格:“。
https://stackoverflow.com/questions/64179576
复制相似问题