C++。我的"hello world"计划有什么问题?
C++. What is wrong with my "hello world" program?
有人可以告诉我这有什么问题吗?当我输入"你好吗"时,它不会回复"我很好"。请帮忙!!
#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::getline
。正如std::cin>>
在发布的代码中得到第一个单词。
cout << "Write something.." << endl;
std::getline (std::cin,x);
if (x == "How are you?"){
cout << "I am fine." << endl;
}
首先,也许你应该输入你好吗?而不是如何让它像你想在代码中检查的那样响应。啊,哈:)
另一件事,也是更严重的事情是,你应该使用std::getline()
而不是std::cin>>
来获取输入,因为后者只会得到第一个单词。
程序不是认知的。如果你在程序中硬编码"你好吗?",你最好打赌,除非你的程序处于故障状态,否则它期望"你好吗?"。您可以通过执行不区分大小写的比较(或将字符串转换为小写)或允许省略问号来缓解限制(但这不是一个真正的问题,是吗?
为了读取整个字符串,您需要使用 getline
.否则,cin
将只提取第一个单词(直到空格)。
std::getline(std::cin, x);
试试这样的事情——
$ 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.
$
使用此语法,您只阅读一个单词。
为了进行调试,请打印您阅读的内容...
读取一行的正确方法是:
getline(cin, x);
我很确定 getline 不会返回尾随的新行,但如果它不起作用,请检查它。
使用 strcmp 比较字符串
strcmp() 返回 0;如果两个字符串相同
returns 1;returns 1 if they are different
int strcmp ( const char * str1, const char * str2 );
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了