C++-使用get()后如何操作字符
C++ - How can I manipulate characters after using get()?
我有一个赋值,在这个赋值中,我们收到一个最多有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
。如果文本行总是具有相同数量的数字,则数组可能很有用。
相关文章:
- 对字符数组中的元素执行逐位操作
- 位移操作和位掩码未检测到重复字符
- 字符串操作 - 字符计数
- 字符的输入/输出操作
- 从格式化输入操作中获取读取字符数
- 使用字符数组堆叠。如何执行"+"和"*"操作?
- 如何使用字符在 cpp 中操作 JPEG
- 打开一个文件,修改每个字符,然后执行反向操作不输出原始文件
- 如何将字符 a= '+'(或字符串 []) 变成实际操作?
- C++-使用get()后如何操作字符
- 将字符数复制到新字符串位置的字符串操作,例如 S[0]
- 在最少的操作中实现字符串所有字符的相同频率。(所有字符的范围从'a'到"z")
- 如何在字符级别操作Unicode字符串
- 操作多字节字符的字符串
- 关于"无符号字符"和"移位"操作的迷你问题?
- C++使用逐位操作从图像中提取字符
- 从 C++ 中的函数操作字符数组缓冲区
- Qt - 在像素操作后显示无符号字符
- 如何跨函数全球化和操作字符数组
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递