我有一个代码:
using namespace std; int main() { char Filename[100]; char st[100][100]; char *argv[100]; std::ifstream infile("data.txt"); std::freopen("output.xls","w",stdout); if (!infile) { cout << " Input file Could not open file." << endl; return 1; } std::string line; while (std::getline(infile,line)) { int a; int length=line.size(); for(a=0;a<=length;a++) { Filename[a]=line[a]; } // one D array to 2D array int b=0; int l=0; strcpy(st[0],"0");// for erase previous value //cout<<st[0]<<endl; for(int j=0;j<=a;j++) { if (Filename[j]==' ') { b++; l=0; strcpy(st[b],"0");// for erase previous value } else { st[b][l]=Filename[j]; l++; } } //.......... // 2D array to reffarence array. for(int k=0;k<=b;k++) { argv[k]=&st[k][0]; cout<<argv[k];// or cout<<st[k]; i get same cout<<"\t"; } cout<<endl; //.............. // Do whatever with the array content } infile.close(); return 0; }数据文件是:(两个字之间的一个空格)testCore 100 100 400 5000 5000“/行结束”testCo 1 4 4 100 100“/行尾”tcore 1 3 4 5 20“/行尾”core 2 3 4 200 4“/行结束”
我的输出是:
我想要的是:我想逐行读取数据文件(这很重要)并在读取一行后分隔每个单词,然后读取另一行。 但问题是在每行的第一个单词的输出中(在第一行的每个单词中)它给出了垃圾输出。 第2栏也有问题。 我的代码有什么问题? 有没有任何改正?
I have a code:
using namespace std; int main() { char Filename[100]; char st[100][100]; char *argv[100]; std::ifstream infile("data.txt"); std::freopen("output.xls","w",stdout); if (!infile) { cout << " Input file Could not open file." << endl; return 1; } std::string line; while (std::getline(infile,line)) { int a; int length=line.size(); for(a=0;a<=length;a++) { Filename[a]=line[a]; } // one D array to 2D array int b=0; int l=0; strcpy(st[0],"0");// for erase previous value //cout<<st[0]<<endl; for(int j=0;j<=a;j++) { if (Filename[j]==' ') { b++; l=0; strcpy(st[b],"0");// for erase previous value } else { st[b][l]=Filename[j]; l++; } } //.......... // 2D array to reffarence array. for(int k=0;k<=b;k++) { argv[k]=&st[k][0]; cout<<argv[k];// or cout<<st[k]; i get same cout<<"\t"; } cout<<endl; //.............. // Do whatever with the array content } infile.close(); return 0; }the datafile is:(one space between two word) testCore 100 100 400 5000 5000 "/end of line" testCo 1 4 4 100 100 "/end of line" tcore 1 3 4 5 20 "/end of line" core 2 3 4 200 4 "/end of line"
my output is:
what I want: I want read the data file line by line(it is important) and separate each word after reading one line,then read another line. But the problem is in output in first word of every-line (in every word of first line also)it give garbage output. and there is problem in 2nd column also. What is the problem of my code? Anyone have any correction?
最满意答案
你正在创建一个大小为100的char数组,它是未初始化的。 然后,你只需要阅读3-8个字符。 但是你要打印出整个缓冲区,包括未初始化的元素。
You're creating a char array of size 100, which is uninitialised. Then, you're only ever reading 3-8 chars into it. but you're printing out the entire buffer, including the uninitialised elements.
更多推荐
发布评论