C++:进入循环后增加新行

C++: Extra new line after entering a loop?

本文关键字:增加 新行 循环 C++      更新时间:2023-10-16

我一月份才开始学习如何编码,在这方面仍然非常非常新!我的代码可能/肯定看起来像垃圾,肯定有一种方法可以提高效率,但我还没有学会它!

我似乎找不到为什么我的显示器中有新行!

输出如下所示:

Student name    Test1    Test2    Test3    Test4    Average    Grade
Ben Smith
90              88       77       55       76.55    A

如果您想尝试,这里是文本文件内容的形成。

90 88 77 55 Ben Smith  
66 77 66 55 Stuart Bit

这是我的完整代码(输出语句接近末尾(:

#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
int main()
{
   string name[25], grade[25];
   string dummy;
   int lineNum=0;
   int x,y;
   int table[25][4]{};
   double average[25]{},classAvg[4]{};
   ifstream in;
   in.open("classData.txt");
   while(getline(in, dummy))
   { 
      lineNum++;
   }
   in.close();
   in.open("classData.txt");
   while(!in.eof())
   {
      for(x=0; x<lineNum;x++)
      {
          for(y=0;y<4;y++)
          {
            in>> table[x][y];
          }
          in.ignore(1, 'n');
          getline(in, name[x]);
      }
   }
   in.close();
   for(x=0; x<lineNum;x++)
   {
      for(y=0;y<4;y++)
      {
          average[x] += table[x][y];
      }
      average[x]= average[x]/4;
   }
   for(int x=0;x<4;x++)
   {
      for(int y=0;y<lineNum;y++)
      {
         classAvg[x]+=table[y][x];
      }
      classAvg[x]=classAvg[x]/lineNum;
   }
   for(int x=0;x<lineNum;x++)
   {
      if(average[x]>= 90)
         grade[x]="A";
      else if(average[x]>= 80)
         grade[x]="B";
      else if(average[x]>= 70)
         grade[x]="C";
      else if(average[x]>= 60)
         grade[x]="D";
      else 
         grade[x]="F";
   }
    cout<<setw(20)<<"Student Name"
    <<setw(20)<<"Test 01"<<setw(20)<<"Test 02"
    <<setw(20)<<"Test 03"<<setw(20)<<"Test 04"
    <<setw(20)<<"Average"
    <<setw(20)<<"Grade"<<endl; //Print headers.
   for(int x=0;x<lineNum;x++)
   {
      cout<<setw(20)<<name[x]; //Print all students' names.
      for(int y=0;y<4;y++)
      { 
         cout<<setw(20)<<table[x][y]; //Print 4 tests per student.
      }
      cout<<setw(20)<<setprecision(2)<<fixed<<average[x]; //Print average of 4 tests.
      cout<<setw(20)<<grade[x]<<endl; //Print the grade of the student.
   }
}

我认为你对于第一次程序员来说做得很好!输出中显示的换行符来自输入文件。

跟:

getline(in, name[x]);

您阅读所有字符,包括末尾的换行符。

之后你可以尝试修剪名称[x]。