C++。我的"hello world"计划有什么问题?

C++. What is wrong with my "hello world" program?

本文关键字:什么 问题 计划 world 我的 hello C++      更新时间:2023-10-16

有人可以告诉我这有什么问题吗?当我输入"你好吗"时,它不会回复"我很好"。请帮忙!!

#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 );