1

我编写了这段代码来从控制台输入读取 N 行并将其放入字符串数组中,但它正在读取 N-1 行有什么建议吗?

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main()
{
int test;
cin>>test;
string *cases=new string[test];
for(int i=0;i<test;i++)
{
    getline(cin,cases[i],'\n');
}

for(int i=0;i<test;i++)
{
    cout<<cases[i]<<endl;
}

system("pause");
return 0;
}
4

1 回答 1

3

假设您的输入是这样的:

2\n
line 0\n
line 1\n

然后在 之后cin>>test,顶部有一个空行:

\n
line 0\n
line 1\n

使用>>只读取它感兴趣的位(即int),然后在流中留下任何其他内容(在这种情况下,只是\n想一想,可能会有各种各样的东西在线上)。 getline读取所有内容,然后从流\n 中删除\n。所以在第一个之后getline,剩下的输入是:

line 0\n
line 1\n

cases[0]包含""(即一个空字符串)。

然后在下一个之后getline

remaining input:
line 1\n

cases[0]: ""
cases[1]: "line 0"

然后循环停止,因为它已经读取了 2 行。这就是问题所在。修复它是另一回事。我更喜欢避免混合>>getline. 但是你可以做一些事情来清除\n流中的拖尾。

编辑:您也可以好好阅读std::vector(该文档可能有点技术性 - 搜索教程)以及using namespace std;

我整理了一种修复它的方法。注意stoi仅是 c++11。如果您没有可用的,您可以尝试使用stringstreamwith>>atoi.

#include <iostream>
#include <vector>
#include <string>
int main()
{
    int inLines = 0;
    //std::cin >> inLines;
    std::string countLine;
    std::getline(std::cin, countLine);
    try
    {
        inLines = std::stoi(countLine);
    }
    catch (...)
    {
        std::cout << "First line must be an integer\n";
        return 1;
    }
    std::vector<std::string> lines(inLines);

    for (int i = 0; i < inLines; ++i)
    {
        std::getline(std::cin, lines[i]);
    }

    for ( auto & s : lines )
    {
        std::cout << s << '\n';
    }
    return 0;
}
于 2013-03-11T11:48:34.987 回答