【问题标题】:Scanning a complete line from a external file in C++ [duplicate]从 C++ 中的外部文件扫描整行 [重复]
【发布时间】:2017-01-04 09:54:52
【问题描述】:

用于从 C++ 文件中扫描完整行:

当我使用inFile >> s; 时,其中 s 是一个字符串,inFile 是一个外部文件,它只是从该行读取第一个单词。

完整代码:(我只是想逐行扫描文件并打印行的长度。)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream inFile;
inFile.open("sample.txt");
long long i,t,n,j,l;
inFile >> t;
for(i=1;i<=t;i++)
{
    inFile >> n;
    string s[n];
    for(j=0;j<n;j++)
    {
        getline(inFile,s[j]);
        l=s[j].length();
        cout<<l<<"\n";
    }
}
return 0;
}

示例.txt

2
3
ADAM
BOB
JOHNSON
2
A AB C
DEF

第一个整数是测试用例,后跟没有单词。

【问题讨论】:

  • 改用std::getline
  • inFile &gt;&gt; t; 读入 long long 它不会读入行尾。这将导致以后的悲伤。两条建议:1. 不要将&gt;&gt;std::getline 混用;2. 使用更好的可变名称。我懒得调试字母汤。

标签: c++ external fstream ifstream ofstream


【解决方案1】:

使用 std::getline 函数;它正是为此目的而制作的。你可以阅读它here。在您的具体情况下,代码将是:

string s;
getline(infile, s);
// s now has the first line in the file. 

要扫描整个文件,您可以将 getline() 放在一个 while 循环中,因为它在文件末尾返回 false(或者如果读取了错误位)。因此你可以这样做:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;    

int main() {
    ifstream inFile;
    inFile.open("sample.txt");
    int lineNum = 0;
    string s;
    while(getline(infile, s) {
        cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
    }
    return 0;
}

【讨论】:

  • 但是如果要扫描整数,我们必须将 '>>' 与 'std::getline' 混合在一起??
  • @SaurabhShubham 使用 getline() 将行转换为字符串 s 后,您可以使用流提取运算符 (">>") 使用字符串流将其拆分。 Here 就是一个例子
猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多