我正在用c ++编写一个程序,我从中读取文本文件中的数据,然后使用排序算法对它们进行排序。我不允许使用文件操作来读取输入。我正在使用" for loop"从文件中读取所有数据。我遇到问题的部分是当我尝试打印文件的最后一部分时,它会搞砸并且无组织。我的文本文件大约是220行,我的程序正在读它,直到文件的最后一部分是我的函数。
我应该在打印后得到这个:
bsort 2015 penalties decr
bsort 2011 yds_per_game incr
bsort range 2010 2015 scrimmage_plays incr
bsort 2012 top_per_game incr
bfind 2013 yds_per_game max
bfind 2015 fum average
bsort range 2011 2013 first_per_game decr
bfind 2014 yds_per_play min
.
.
.
但我明白了:
bsort2015penaltiesdecr
bsort20102015scrimmage_playsincr
2013yds_per_gamemaxbsort20112013first_per_gamedecr
2010third_attmedianbsort20112013pts_per_gamedecr
bsort20132015top_per_gameincr
bsort2014team_nameincr
我正在使用if语句打印此部分,这是我的代码的一部分:
cin >> c; //Read number of commands
cout << c << endl; //Print the number of commands
cin.ignore();
char** commands = new char*[c]; //Creat a new array type char to read commands, read the complete line
//Read commands
for(int i = 0; i<c; i++)
{
commands[i] = new char[256]; //Read the array of the lines
}
string next; //Declare next type string
for(int i = 0; i <= c - 1; i++){
cin>>commands[i]; //read the command name
if(strcmp(commands[i], "bsort") == 0) // check wether it's bsort or not
{
cout<<commands[i];
cin>>next; // if it is bort, we get the next string
if(next.compare("range") == 0)
{
int start_year , end_year;
cin>>start_year;
cout<<start_year;
cin>>end_year;
cout<<end_year;
string field;
cin>>field;
cout<<field;
string order;
cin>>order;
cout<<order<<endl;
cin.ignore();
bsort(stats,y, start_year, end_year, field, order);
}
else
{
int year = atoi( next.c_str() );
cout<<year;
string field, order;
cin>>field;
cin>>order;
cout<<field;
cout<<order<<endl;
cin.ignore();
bsort(stats, y, year, field, order);
//Call bsort function by passing only 1 year in the bsort function
}
}
else if(strcmp(commands[i], "bfind") == 0)
{
int year;
cin >> year;
string field, order;
cin>>field;
cin>>order;
cout<<year;
cout<<field;
cout<<order;
cin.ignore();
bfind(stats, y, year, field, order);
}
非常感谢任何帮助。
答案 0 :(得分:1)
您忘记在输出中添加空格。如果要在两个输出之间显示空格,则必须将其放在那里。你可以用
做到这一点cout << some_variable << " ";
如果您之间有cout
两次或多次调用而没有cin
,则需要添加某种分隔符。在
else if(strcmp(commands[i], "bfind") == 0)
{
int year;
cin >> year;
string field, order;
cin>>field;
cin>>order;
cout<<year;
cout<<field;
cout<<order;
cin.ignore();
bfind(stats, y, year, field, order);
}
您输出year
,field
和order
而没有任何分离。如果你想要它们全部在一行上,那么你可以将它改为
else if(strcmp(commands[i], "bfind") == 0)
{
int year;
string field, order;
cin year >> field >> order;
cout << year << " " << field << " " << order;
cin.ignore();
bfind(stats, y, year, field, order);
}