C++ C++;。“我的”怎么了;“你好,世界”;程序
谁能告诉我这有什么问题吗。当我输入“你好吗”时,它不会回答“我很好”!请帮忙C++ C++;。“我的”怎么了;“你好,世界”;程序,c++,C++,谁能告诉我这有什么问题吗。当我输入“你好吗”时,它不会回答“我很好”!请帮忙 #include <iostream> #include <string> using namespace std; int main() { string x; cout << "Write something.." << endl; cin >> x; if (x == "How are you?") {
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x;
cout << "Write something.." << endl;
cin >> x;
if (x == "How are you?") {
cout << "I am fine." << endl;
}
system("PAUSE");
}
#包括
#包括
使用名称空间std;
int main()
{
字符串x;
cout x;
如果(x==“你好吗?”){
cout首先,也许你应该输入你好吗?而不是你好吗,让它像你想在代码中检查的那样响应。啊,哈:)
另一件事情,也是更严重的事情,是你应该使用std::getline()
来获取输入,而不是std::cin>
,因为后者只会获取第一个单词。使用std::getline
。
Asstd::cin>
获取发布代码中的第一个单词
cout << "Write something.." << endl;
std::getline (std::cin,x);
if (x == "How are you?"){
cout << "I am fine." << endl;
}
cout程序无法识别。如果您将“你好吗?”硬编码到程序中,您最好确信,除非您的程序处于故障状态,否则它期望“你好吗?”。您可以通过执行不区分大小写的比较(或将字符串转换为小写)或允许省略问号来减轻限制(但这不是一个真正的问题,是吗?)
为了读入整个字符串,您需要使用getline
。否则,cin
将只提取第一个单词(直到空格)
使用此语法,您只能阅读一个单词
要进行调试,请打印您阅读的内容
读取行的正确方法是:
getline(cin,x);
我很确定getline不会返回尾随的新行,但是如果它不起作用,请检查它。使用strcmp比较字符串
strcmp()返回0;如果两个字符串相同
returns 1;returns 1 if they are different
int strcmp ( const char * str1, const char * str2 );
试试这样的东西-
$ cat hello.cc
#include <iostream>
#include <string>
int main() {
using namespace std;
string x;
cout << "Write something.." << endl;
getline(cin, x);
if (x == "How are you?") {
cout << "I am fine." << endl;
}
}
$ g++ hello.cc
$ ./a.out
Write something..
How are you?
I am fine.
$
$cat hello.cc
#包括
#包括
int main(){
使用名称空间std;
字符串x;
你能试着打印x来看看它是什么吗?当然不能。你说如果你输入“你好吗?”“你好吗?”是另一个字符串。我并不想粗鲁,但为什么在等待答复时在问题结束时不加问号。格式提示:请在发布前将制表符转换为空格。否则,您的代码会看起来乱七八糟。(我刚刚做了一次编辑,解决了这个问题。)OP使用的是std::string
,因此这里不需要使用C风格的字符串比较。C++的
为运算符==()
这将把std::string
与const char*
进行比较。谢谢,这对我来说很有用。如何在switch语句中使用此输入而不是if??。@user2998832问另一个问题,并接受此问题的答案。@user2998832你不能,std::string
不能在switch语句中使用。你需要坚持>如果
。非常感谢您提供的信息,我问了同样的问题!!std::getline
提取换行符,但不包括在字符串中。
$ cat hello.cc
#include <iostream>
#include <string>
int main() {
using namespace std;
string x;
cout << "Write something.." << endl;
getline(cin, x);
if (x == "How are you?") {
cout << "I am fine." << endl;
}
}
$ g++ hello.cc
$ ./a.out
Write something..
How are you?
I am fine.
$