我收到了一个名为blabla.txt的文本文件,其格式如下:
1
2 3
4 5 6
我可以编写哪些代码来格式化它,使其如下所示:逗号和新行如下所示:
1,
2, 3,
4, 5, 6
答案 0 :(得分:0)
试试这个..
#include <iostream>
using namespace std;
int main()
{
int rows,i,j,k=0;
cout<<"Enter number of rows: ";
cin>>rows;
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;++j)
cout<<k+j<<",";
++k;
cout<<endl;
}
return 0;
}
答案 1 :(得分:0)
这是你的作业;)
#include <string>
#include <cctype>
#include <stdio.h>
int main(int argc, const char* argv[])
{
FILE * f = fopen("E:\\temp\\crap.txt", "wt");
const char *t = "1\n2 3\n4 5 6 ";
fwrite(t,1,strlen(t),f);
fclose(f);
f = fopen("E:\\temp\\crap.txt", "r+t");
fseek(f, 0L, SEEK_END);
size_t fs = ftell(f);
fseek(f, 0L, SEEK_SET);
std::string input;
input.resize(fs);
fread(&input[0], 1, fs, f);
std::string output;
output.reserve(2 * input.length());
bool inText = false;
for (auto c : input)
{
if (!isspace(c)) inText = true;
else
{
if (inText)
output.push_back(',');
inText = false;
}
output.push_back(c);
}
fseek(f, 0L, SEEK_SET);
fwrite(output.data(), 1, output.length(), f);
fclose(f);
return 0;
}
使用clang编译并执行FreeBsd(几乎是mac;))这个程序产生:
more crap.txt
1,
2, 3,
4, 5, 6,
在Windows上产生了相同的输出。
答案 2 :(得分:-1)
如果我理解你的观点,那么下面是你的解决方案。
public void Text(string text) { 串行; int counter = 0; string newline = string.Empty; System.IO.StreamReader file = new System.IO.StreamReader(@&#34; E:\ BlahBlah.txt&#34;); while((line = file.ReadLine())!= null) {
var words = line.Split(' ');
if (words.Count() > 1)
{
foreach (var word in words)
{
newline += word + ", ";
}
}
else
{
newline = line + ", ";
}
counter++;
}
newline = newline.Trim(' ').Trim(',');
Response.Write(newline.ToString() + System.Environment.NewLine);
file.Close();
}