通过读取Excel表格为c文件中的variables赋值

我需要通过阅读一个Excel工作表来为C文件中的variables赋值。 我已经写了一个代码,但只有最后一个variables已被分配一个值,因为我已经用于循环。它正在覆盖分配给以前的variables的值,因为我分配值后创build一个不同的输出文件。

#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string s1, s2, s3,s4; string filename, text, line; string cfilename,funcname, signal, value; int i , k , m; cout << "Enter excel filename" << endl; cin >> filename; cout << "How many lines of text are in the file?" << endl; cin >> m; fstream file(filename); if (!file) { cerr << "No such file exists." << endl; exit(1); } if (file.is_open()) { while (file.eof()==0){ for (k = 0; k < m; k++) { //Loops for as many lines as there are in the file for (i = 0; i < 4; i++) { //Loops for each comma-separated word in the line if (i == 0){ getline(file, text, ','); cfilename=text; cout << cfilename << '\t';} else if (i == 1){ getline(file, text, ','); funcname=text; cout << funcname << '\t';} else if (i == 2){ getline(file, text, ','); signal=text; cout << signal << '\t';} else if (i == 3){ getline(file, text, '\n'); value=text; cout << value << '\n';} } string s1=signal,s2=value; s2 = s2 + "; //"; int offset, inset; string line; string search=s1; fstream cfile(cfilename); fstream fileOutput; fileOutput.open("output.c"); if(cfile.is_open() && fileOutput.is_open()) { while(!cfile.eof()) { getline(cfile, line); if ((offset = line.find(funcname)) != string::npos){ cout << "found: " << funcname << endl; string line1; fileOutput << line << '\n'; skip: while(getline(cfile,line1)){ if((inset=line1.find(search, 0)) !=string::npos){ cout<<"found: " << search << endl; string s3 = s1+ "=" +s2; //cout<<s3; line1.replace( inset, inset+s1.size(), s3 );} fileOutput << line1 << '\n'; goto skip; } getchar(); } fileOutput << line << '\n'; } cfile.close(); fileOutput.close(); } } } } file.close(); getchar(); return 0; } 

我正在尝试search一个函数,然后在该函数中的variables。

在这里需要一些帮助。

我不确定这是这个问题,但是…我while ()东西太多了。

当你把这个文件的m行写出来的时候,你的

 while (file.eof()==0) 

结果是真的,因为你没有读过文件末尾的任何东西。

所以你读了其他的m行(失败,但没有阅读成功的控制)。

编辑:我认为你应该写一些像

 cout << "Enter excel filename" << endl; cin >> filename; fstream file(filename); if (!file) { cerr << "No such file exists." << endl; exit(1); } while ( getline(file, cfilename, ',') && getline(file, funcname, ',') && getline(file, signal, ',') && getline(file, value, '\n')) { cout << cfilename << '\t' << funcname << '\t' << signal << '\t' << value << '\n'; string s1=signal,s2=value; [...] 

该程序完全按照您要求的方式执行:

  • 您逐行读取CSV文件(excel格式为二进制!)
  • 对于csv中的每一行:
    • 擦除输出文件,因为你打开一个fstream而不指定ios::ate
    • search源文件中的内容并写入输出文件。

当你从input的CSV文件中删除每一行的输出文件时,你不能得到比上一次更多的操作。

如果你在循环之外打开一次输出文件就简单多了。

而… while (file.eof() == 0)是一个反模式。 尝试读取一行之前,您看看是否已达到文件结尾,然后在第一个getline设置了eof标志时读取4个值。 你必须在阅读之后立即testingeof,而不是之前…