在C++中显示文件中文本字符串的正确格式的问题

mlmc2os5  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(72)

我在从文件中检索文本(一串数字)时遇到了正确格式的问题。我的目标是以控制台格式显示它:

number number number number ... number

字符串
但它以形式显示,其中每个数字显示在单独的行中,例如:

6
928
81
4
496
3
8
922
0
5
39
731
53


所需格式:

6 928 81 4 496 3 8
922 0 5 39 731 53



示例输入文件(start.txt)如下所示:

6 928 81 4 496 3 8
922 0 5 39 731 53
6 3 48 9 15 971 48
631 30 7 04 31 96
18 78 409 30 55 6
0 75 8 4 0 9 73 61 3
8 36 40 21 05 825
66 4 7 9 05 96 3
6 43 5 3 39 3 07
77 0 2 76 7 8 3 5


代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>  
#include <random>
#include <chrono> 
#include <cmath> 
#include <string>
#include <string.h>

using namespace std;

int main(int argc, char* argv[])
{

    {
        const string OSOBNIKI{ "start.txt" };

        ifstream file(OSOBNIKI);
        if (file)
        {
            string chromosom;

            while (file>> chromosom)
                cout << chromosom << endl;
        }
    }
    return 0;
}


我一直在尝试它与多个cout的。但我还没有找到正确的解决方案,以格式化它作为在原始文件。这将是最好的使用某种循环,因为我猜。

ozxc1zmp

ozxc1zmp1#

打印std::endl会在输出中写入一个新行,这就是为什么每个数字都在自己的行上打印出来。
您希望仅在输入中遇到新行时才打印新行,但operator>>会忽略前导空格,包括新行。因此,您当前的代码无法知道何时遇到新行。
要执行您想要的操作,请使用std::getline()逐行读取文件,并使用std::istringstream从每行读取数字。
举例来说,您可以:

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

using namespace std;

int main(int argc, char* argv[])
{
    const string OSOBNIKI{ "start.txt" };

    ifstream file(OSOBNIKI);
    string line;
    int chromosom;

    while (getline(file, line)) {
        istringstream iss(line);
        while (iss >> chromosom) {
            cout << chromosom << ' ';
        }
        cout << endl;
    }

    return 0;
}

字符串

相关问题