为什么这个程序打印出预期结果的反面?
Why is this program printing the reverse of the expected result?
#include <bits/stdc++.h>
using namespace std;
int main()
{
string in_code;
std::cin >> in_code;
int word;
word = in_code.find(" ");
in_code.erase(0, (word + 1));
cout << in_code << endl;
}
当我输入 "Jhon is_a_good_boy" 时,这个程序应该 return "is_a_good_boy"。但它打印 "Jhon"。请帮我解决这个问题。
您可能应该使用 getline 来处理此问题,以便捕获输入的整行并在使用 string.find
时进行验证
下面的评论示例。
#include <string>
#include <iostream>
int main()
{
std::string in_code; //String to store user input
std::getline(std::cin, in_code); //Get user input and store in in_code
int word = in_code.find(" "); //Get position of space (if one exists) - if no space exists, word will be set to std::string::npos
if (word != std::string::npos) //If space exists
{
in_code.erase(0, word + 1); //erase text before & including space
std::cout << in_code << std::endl;
}
else
{
std::cout << "The entered input did not contain a space." << std::endl;
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
string in_code;
std::cin >> in_code;
int word;
word = in_code.find(" ");
in_code.erase(0, (word + 1));
cout << in_code << endl;
}
当我输入 "Jhon is_a_good_boy" 时,这个程序应该 return "is_a_good_boy"。但它打印 "Jhon"。请帮我解决这个问题。
您可能应该使用 getline 来处理此问题,以便捕获输入的整行并在使用 string.find
时进行验证下面的评论示例。
#include <string>
#include <iostream>
int main()
{
std::string in_code; //String to store user input
std::getline(std::cin, in_code); //Get user input and store in in_code
int word = in_code.find(" "); //Get position of space (if one exists) - if no space exists, word will be set to std::string::npos
if (word != std::string::npos) //If space exists
{
in_code.erase(0, word + 1); //erase text before & including space
std::cout << in_code << std::endl;
}
else
{
std::cout << "The entered input did not contain a space." << std::endl;
}
return 0;
}