为什么我的代码只接受输入而没有返回任何输出?

时间:2020-03-31 06:29:38

标签: c++

在此代码中,用户将输入多行(字符串),然后将这些行打印为输出。输入将由EOF终止。在我的代码中,这仅接受输入,而不返回任何输出。这段代码有什么问题?

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    string s = "";

    int i=0;
    while (true) {
        char str = getchar();
        if (str!=EOF ||str!='\n') {
            i++;
            s = s+str;
        } else {
            break;
        }
    }

    cout<<s;

    return 0;
}
Sample Input:

- The current platform was developed in 2005.
- It uses a very old version of Joomla, which makes maintenance a very difficult task.
- The way people uses internet services has changed a lot in 15 years.
- The new platform MUST be Open Source.

Sample Output:

- The current platform was developed in 2005.
- It uses a very old version of Joomla, which makes maintenance a very difficult task.
- The way people uses internet services has changed a lot in 15 years.
- The new platform MUST be Open Source.

1 个答案:

答案 0 :(得分:4)

str != EOF || str != '\n'

某些奇怪的量子力学领域的简称,该str变量不能同时为EOF '\n' :-)

  • 对于str的{​​{1}}值,这将为您提供EOF,即false or true
  • 对于true的{​​{1}}值,这将为您提供str,即\n
  • 对于其他任何true or false值,这将为您提供true,即str

换句话说,它将从不脱离该循环。您需要:

true or true

无论如何,即使有此修复程序,它也会停止对第一个换行符进行的所有处理,而我认为这不是您想要的。您可能应该只检查true并摆脱换行检查,例如:

str != EOF && str != '\n'

还要注意,我使用EOF类型作为#include <iostream> #include <cstdio> using namespace std; int main() { string s = ""; while (true) { int str = getchar(); if (str == EOF) break; s += static_cast<char>(str); } cout << s; return 0; } 的返回值-这是标准做法,因为它需要能够返回每个可能的字符 plus 文件结束指示。


您可能还希望完全重新考虑对旧版int函数的使用,C ++的完美getline function可以将整个行作为字符串。这样的事情将是一个很好的起点:

getchar()