因此,此代码的任务是复制学生'从csv excel表到xcode的名称和等级,然后将它们放入数组并将它们放入新的Excel工作表中。我似乎遇到的问题是getline没有进入下一行。为了确保在这段代码中某处不会出现导致这种情况发生的错误,我编写了一个非常小且完全不同的程序来查看getline是如何工作的,并发现它不会跳到下一行。事实上,如果我将字符数量提高到一个很高的数字,它只会将整个excel信息复制到数组中。这是我的代码:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
char line[80];
string students[100];
int grades[50][20];
char *p;
int r;
int q;
void read_sheet();
void print_sheet();
int main() {
read_sheet();
print_sheet();
return 0;
}
void read_sheet(){
ifstream file1("/Users/JohnnyD/Downloads/Project_MAC101.csv");
file1.getline(line, 79); // this puts everything from the first line of the
// excel sheet into the array line
for(r=0;r<50||(!file1.eof());r++){ // this is a loop that goes up to
// either the amount of students
//(50 is max) or the end of the
file1.getline(line, 79); // this is suppose to put everything
//from the second line into the array
// line, but I don't think it is doing
// that.
p=strtok(line,","); // this takes everything from the first
// line that is before the comma and
//puts it into p.(should be only a single
// student's name
students[r]=p; // this puts the name into the array
// called students
cout << students<<endl; // this is only a test to see if the names
// are going properly to the array. I
// wouldn't normally have this in the code.
// This is where I found out that it's not
// skipping to the next line because the
// output just spits out "name" over and
// over again which means that it never got
// passed the first word in the excel sheet.
// ("name" is the first word in the first
// line in the excel sheet)
for(q=0;q<20;q++){ // this is a loop that goes to the end of
// the column where 20 is the max amount
// of grades
p=strtok(NULL,","); // puts each grade before the comma into p.
if(p==NULL) // if it's the end of the line, break out
break; //of the loop.
grades[r][q]=atoi(p); // this changes the string to integer and then
// puts it into the array grades
}
}
file1.close();
}
void print_sheet(){
ofstream file2("testing.csv");
for(int y=0;y<=r;y++){
file2<<students[y];
for(int h=0;h<q;h++){
file2<<grades[y][h];
}
file2<<endl;
}
file2.close();
}
这是我用来测试以查看getline是否实际移动到下一行的代码。
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
char line[80];
int main() {
ifstream file1("/Users/JohnnyD/Downloads/Project_MAC101.csv");
file1.getline(line, 79);
cout << line<<endl;
file1.getline(line, 79); // shouldn't this then go to the next line?
cout << line<<endl; // It doesn't. It only repeats the first getline
return 0;
}
答案 0 :(得分:0)
从文件中读取的通常习惯是使用while
语句。
在您的情况下,您可以使用另一个变量限制它:
const unsigned int maximum_records = 50U;
unsigned int record_count = 0U;
std::string text_line;
// ...
while (getline(datafile, text_line) && (record_count < maximum_records))
{
//...
++record_count;
}
如果文件操作失败或已达到最大记录,则输入会话将终止。