我for在我的程序中执行了以下循环,我无法看到它的设计与我收到的输出有何关联.
cout << no_of_lines << endl;
for (int count = 0; count < no_of_lines + 1; count ++)
{
getline(Device, line, '=');
cout << line << endl;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
3
DeviceName
GPU
Manufacturer
Intel
GraphicalRam
128MB
Run Code Online (Sandbox Code Playgroud)
这是文件DeviceList
DeviceName=GPU
Manufacturer=Intel
GraphicalRam=128MB
Run Code Online (Sandbox Code Playgroud)
在循环中,no_of_lines指的是文件中的行数,在本例中为3.我提供此输出作为验证,即循环每行仅执行一次.谁能告诉我为什么这个循环执行的次数比预期的多?我猜这是因为我包含了=作为deliminator,并且循环在某种程度上在递增之前执行了额外的时间,但是为什么它会在最后一行的deliminator上停止,要求我在循环限制中加1 ?
这个http://www.cplusplus.com/reference/string/getline/是你的朋友.文档说当将删除字符传递给getline时,它会读取Delem char或找到文件结尾.'\n'没有区别对待.一旦发现DELEM烧焦它丢弃并填充线不管它一直读到了这一点.下次你打电话给getline时,它会继续从它离开的地方读取.所以在这种情况下,每个调用如下所示.
DeviceName
GPU\nManufacturer
Intel\nGraphicalRam
128MB\n
Run Code Online (Sandbox Code Playgroud)
上面字符串中的'\n'基本上是换行符.它不是真正的反斜杠,后跟n(2个字符).它只是一个换行符'\n'.出于理解目的,我就这样使用它.
为清楚起见,这里是完整的代码(编译和测试).
#include <iostream>
#include <string>
using namespace std;
int main()
{
int no_of_lines = 3;
string line;
cout << no_of_lines << endl;
for (int count = 0; count < no_of_lines + 1; count++)
{
getline(cin, line, '=');
cout << line << endl ;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
到现在为止,我希望你明白为什么你需要4次拨打getline.