我有一个简单的问题......假设我想从标准输入中读取行,只要有东西,但我不知道它将是多少行。例如,我正在做功课,输入是
a
ababa
bb
cc
ba
bb
ca
cb
我不知道具体会有多少行,所以我尝试了
string *line = new string[100];
int counter = 0;
while(getline(cin,line[counter]))
{
counter++;
}
但它不起作用......感谢您的帮助。
我有一个简单的问题......假设我想从标准输入中读取行,只要有东西,但我不知道它将是多少行。例如,我正在做功课,输入是
a
ababa
bb
cc
ba
bb
ca
cb
我不知道具体会有多少行,所以我尝试了
string *line = new string[100];
int counter = 0;
while(getline(cin,line[counter]))
{
counter++;
}
但它不起作用......感谢您的帮助。
如果您希望输入以空行结束,那么您必须对其进行测试。例如。
string *line = new string[100];
int counter = 0;
while (getline(cin, line[counter]) && line[counter].size() > 0)
{
counter++;
}
恭喜您getline()正确使用 BTW。与您得到的某些答案不同。
您可以通过以下方式获取行数:
string *line = new string[SIZE];
int lines = 0;
while(lines < SIZE && getline(cin, line[lines]) && line[lines].size() > 0)
{
cout << input_line << endl;
lines++;
}
不要忘记检查是否添加的行数不超过字符串行可以处理的大小,否则会出现分段错误。
我能想到的最简单的线路计数器是这样的:
#include <string>
#include <iostream>
unsigned int count = 0;
for (std::string line; std::getline(std::cin, line); )
{
++count;
}
std::cout << "We read " << count << " lines.\n";
测试:
echo -e "Hello\nWorld\n" | ./prog
如果您想打折空行,请if (!line.empty()) { ++count; }改为说。
这应该有效:
int cont = 0;
string s;
while(cin >> s) { //while(getline(cin,s)) if needed
if(s.empty()) break;
++cont;
}
您也可以为此使用文件结束标记。它的用法是这样的。
std::ifstream read ("file.txt") ;
while(!read.eof())
{
//do all the work
}
如果已到达文件末尾,则此函数返回 true。所以它会一直持续到你遇到它。
编辑:
正如评论中提到的那样,该方法eof可能很危险并且无法提供所需的结果。因此,无法保证它会在每种情况下运行。您可以在这里查看何时可能发生这种情况。