我正在通过一本书自学C++,但在练习中遇到了困难。我的任务是将一个字符串分成两部分,每个部分由一个空格分隔,并忘记其余的部分,但出于某种原因,我的代码没有忘记其余的部分。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string original;
string first;
string second;
bool firstDone = false;
bool secondDone = false;
int firstSpace = 0;
int secondSpace = 0;
cout << "Enter string: ";
getline(cin, original);
cout << "The original string is: " << original << endl;
for(int i = 0; i < original.length(); i++)
{
if(original[i] == ' ' && !firstDone){
firstSpace = i;
firstDone = true;
}
else if(original[i] == ' ' && !secondDone){
secondSpace = i;
secondDone = true;
}
}
cout << "The first space is at: " << firstSpace << endl << "The second space is at: "
<< secondSpace << endl;
first = original.substr(0, firstSpace);
second = original.substr(firstSpace + 1, secondSpace);
cout << "The first string is: " << first << endl << "The second string is: "
<< second << endl;
return 0;
}
当我运行它时,我得到了以下输出:
如你所见,第二个字符串是“test2 test3”,但它应该只是“test2”。有人能指出我做错了什么吗?输入字符串:test1 test2 test3
原始字符串为:test1 test2 test3
第一个空格位于:5
第二个空格位于:11
第一个字符串为:test1
第二个字符串为:test2 test3
P.S. 我在书中的进度不是很远,我在网上找到的其他解决方案都有许多变量和其他我不熟悉的函数,所以如果可能的话,请限制答案的风格。