0
所以對於這個代碼的任務是學生的姓名和等級從CSV複製Excel表單到xcode中,然後把它們放進陣列和把它們放入一個新的Excel表。我似乎遇到的問題是getline不會進入下一行。爲了確保有這個代碼,會導致這樣的事情發生的地方是不是一個錯誤,我寫了一個非常小的,完全不同的程序,看看如何函數getline工作,發現它並沒有跳到下一行。事實上,如果我將字符數量提高到一個很高的數字,它只會將整個Excel信息複製到數組中。這裏是我的代碼:函數getline重複同一線(C++)(xcode中)
#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;
}
'(!file1.eof())'是不是一個很好的循環條件。 [C++ - 爲什麼iostream :: eof在循環條件內被認爲是錯誤的? - 堆棧溢出(http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – MikeCAT
我很驚訝,'COUT <<學生<< ENDL; '打印一個字符串。 – molbdnilo
你真的想繼續EOF只是因爲'r'未達到50後,從'file1'讀書?我想你打算使用'&&'。 – starturtle