从文件中检索文本(一串数字)后,我在正确格式化文本时遇到问题。我的目标是以控制台格式显示它:
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。但我还没有找到正确的解决方案将其格式化为原始文件。正如我猜测,最好使用某种循环。
打印
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;
}