从同样包含字符串的.txt文件中读取整数和双精度

Reading integers and double from .txt file which also contains strings

本文关键字:读取 整数 双精度 文件 txt 包含 字符串      更新时间:2023-10-16

我想写一个从文件中读取文本行的程序。每行包含多个字符串、一个整数和一个双值。行数事先不知道(即程序需要读取行直到文件结束),每行的长度也不知道。while循环检查线路是否按以下方式排序:

 --  string -- integer -- double --- string  
Cat.     3:           18.00 Kr.       [ Tvål ]    
Cat.     1:           14.50 Kr.       [ Äppelmos Bob ]     
Cat.     1:           12.00 Kr.       [ Coca Cola 2 lit. ]     
Cat.     1:           18.00 Kr.       [ Kroppkakor 4 st. ] 

问题是最后一个字符串包含几个空格,因此程序不会将其视为一个完整的字符串。最后一个字符串像几个字符串一样被接受,我在屏幕上只看到Cat。3:18.00 Kr。而不是整个行列表。

我试着处理这样的程序:

double doubleValue;
int intValue;
string str1, str2, str3;
ifstream infile("Register.txt", ifstream::in);
while (infile >> str1 >> intValue >> str2 >> doubleValue >> str3)
{   
   cout << intValue << " " << doubleValue << endl;
}

提前谢谢。

这是因为operator>>将在空白处停止解析。

要计算,您可以先使用std::getline()读取整行。然后,解析前四个部分(通过应用std::stringstream),最后通过再次调用std::getline()获得剩余部分。

#include <sstream>
using namespace std;
string line;
while (getline(infile, line)) // read the whole line from the file
{
    stringstream ss(line);
    ss >> str1 >> intValue >> str2 >> doubleValue; // pause the first four parts
    getline(ss, str3); // parse the remaining part to str3, e.g. "Kr. [ Tvål ]"
}

你可以一直使用fscanf,它会让你,只要你知道格式:

fscanf(f, "%s %d [ %[^x5D]x5D %lf", str1, &int1, str2, &double1);

我个人更喜欢scanf,这里有一个简单的表格:

fmt   meaning
%s    non-whitespace string
%d    integer
%u    unsigned integer
%ld   long
%lu   unsigned long
%f    float
%lf   double
%llf  long double

它还处理特殊格式,但这超出了本文的范围。但如果你说有一个这样的文件,它是有用的:

30.1 multi word string

你可以通过阅读

scanf("%lf %[^n]n", &mydouble, strbuf);

偏好是这里的关键,但我建议你使用fscanf进行

fscanf(FILE *f, char *fmt, ...);

http://www.manpagez.com/man/3/fscanf/

多亏了herohuyong tao,它才起作用。这是一个完整的代码片段,允许读取包含字符串、整数、双精度值的.txt文件,并且只打印整数和双精度值
这是一个txt文件中的一部分。

Cat.     3:           14.50 Kr.       [ Äppelmos Bob ]     
Cat.     2:           12.00 Kr.       [ Coca Cola 2 lit. ]     
Cat.     5:           18.00 Kr.       [ Kroppkakor 4 st. ]
..........
..........

解决方案如下。

    using namespace std;
        cout << "Category totals for last opening period: " << endl;
        double doubleValue;
        int intValue;
        string line, str, str2, str3;
        ifstream infile("Register.txt", ifstream::in);
        getline(infile, line);
        while (getline(infile, line))
        {   
            stringstream infile(line);
            infile >> str >> intValue >> str2 >> doubleValue;
            getline(infile, str3);
            cout << endl;
                cout << setw(3) << str << setw(1) << intValue << setw(7)                                                 << str2 << doubleValue << str3;
        cout << endl;
        }