C++ 只有最后一行保存在c++;

C++ 只有最后一行保存在c++;,c++,file-io,C++,File Io,我的代码只保存最后一行,例如,如果我输入1 abc,然后按enter键,然后键入2 def,则只有2 def保存在txt文件中。 这是我的密码:- int main() { ofstream rankings; rankings.open("rankings.txt"); cout << "Enter rank of the Student <space> followed by Name\n" "Press Ctrl+Z to quit"<< en

我的代码只保存最后一行,例如,如果我输入1 abc,然后按enter键,然后键入2 def,则只有2 def保存在txt文件中。 这是我的密码:-

int main()
{
 ofstream rankings;
 rankings.open("rankings.txt");
 cout << "Enter rank of the Student <space> followed by Name\n"
  "Press Ctrl+Z to quit"<< endl;
 int rank;
 string name;
 while (cin >> rank >> name);
 {
  rankings << rank << ' ' << name << endl;

 }
 rankings.close();


 return 0;
}
intmain()
{
流排名;
排名.open(“rankings.txt”);
cout-rank>>名称);
{

排名您的
while
循环后有一个多余的分号:

while (cin >> rank >> name);
                        // ^
这将在以后的代码中打开一个新块,并为您留下最少的输入值

若要修复,请将循环更改为

while (cin >> rank >> name) {
  rankings << rank << ' ' << name << endl;
}
while(cin>>排名>>姓名){

排名您的
while
循环后有一个多余的分号:

while (cin >> rank >> name);
                        // ^
这将在以后的代码中打开一个新块,并为您留下最少的输入值

若要修复,请将循环更改为

while (cin >> rank >> name) {
  rankings << rank << ' ' << name << endl;
}
while(cin>>排名>>姓名){

排名,不使用Ctrl+Z键退出,而是使用Ctrl键退出+D@GerardRozsavolgyi这取决于操作系统/终端。你是对的,所以只要说在Linux和MacOS下应该是CTRL+Z,不要用CTRL+Z退出,而是用CTRL+D@GerardRozsavolgyi这取决于操作系统/终端。你是对的,所以只要说在Linux和MacOS下应该是CTRL+D