C++-使用get()后如何操作字符

C++ - How can I manipulate characters after using get()?

本文关键字:操作 字符 何操作 使用 get C++-      更新时间:2023-10-16

我有一个赋值,在这个赋值中,我们收到一个最多有40个名称(>10个字符)、姓氏(>12个字符),id#(总是6个字符)和6个等级(必须删除最低的一个)的文件,并且我被限制使用字符串库。

所以基本上是这样的(是的,数据之间有任意数量的空间):

Adam Zeller    452313  78   86    91  64    90 76
Barbara Young 274253 88   77 91 66  82      93
Carl Wilson  112235  87 99  76 15 95 94
Alec Burmeister 234689 45 76 98     54 12 8 

最终它需要看起来像:

Last_name   First_name      ID         Average_Score       Grade
Zeller      Adam            452313     82.3                B

我目前一直在为getline()和get()而挣扎,我可以选择使用其中任何一个(我不能使用cin>>…来接收数据)

我尝试过同时使用这两种方法,但getline给了我太多的错误,到目前为止,get()似乎是最有前途的,尽管我可能错了。

我现在有这个:

const int SIZE = 256;
char student_list[SIZE];
char input_filename[40] = "student_input.txt",
output_filename[40] = "student_results.txt";
Student student[40]; // I want to use a struct, but still trying to figure 
// out how to make the characters into variables so                         
// that I can manipulate the values.
fstream fin;
fin.open(input_filename, ios::in);
if(fin.fail())
{
cout << "ERROR - COULD NOT FIND INPUT FILE  nn";
return 1;
}
char c;
while (fin.get(c))         // loop getting single characters
{
if((c == ' '))
c = 'b';
else if(c == 't')
c == 'b';
else
cout << c;
}
cout << "nnProgram successfully terminated!n";
fin.close();
return 0;

我知道这段代码有点缺陷,因为这只会给我带来输出,但它的工作方式也是我所期望的。。它只是去掉了所有的空格和\t。我所有的数据都在那里(与getline相比,getline吃掉了Adam Zellers行中的最后一个值……只有他的,而不是其他人的idk why。)

AdamZeller452313788691649076
BarbaraYoung274253887791668293
CarlWilson112235879976159594
AlecBurmeister23468945769854128 

这就是我得到的输出,但因为我使用的是char c而不是数组,所以我不能将值输出到外部。另外,似乎即使我可以使用数组,它也不起作用,因为每个名字和姓氏的长度都不同,所以我不能为每个学生硬编码。。。

不管怎样,我做这件事是比它应该做的更复杂,还是我走的路是正确的?我不知道如何操作每个单独的字符,或者将每个字符集(名称、最后一个、id、等级)存储到变量中,因为它们都是单独的字符而不是字符串。

您可以通过基于空间分离的解析来简化您的生活:

std::string first_name;
std::string last_name;
int values[7];
while (fin >> first_name)
{
fin >> last_name;
for (unsigned int i = 0U; i < 7; ++i)
{
fin >> values[i];
}
}

一个更好的方法是将所有这些变量放入一个结构中,并为该结构重载operator>>

另外,将数组更改为std::vector。如果文本行总是具有相同数量的数字,则数组可能很有用。