将文本光标移动到新行
Move text cursor to new line
我有一个文本文件,看起来像这样:
Name_of_st1 67 5 87 4 78 4
Name_of_st2 89 5 56 3 79 4
...
我写了一个程序,它读取数据并创建一个学生向量和它自己的主题向量。程序正确读取第一行,但当我要求它写出第二个学生的名字时,std::cout
显示垃圾。下面是代码:
struct Subject {
int mark0;
int mark1;
};
struct Student {
char name[50];
char surname[50];
vector<Subject>my_marks;
};
istream& operator>>(istream& is, Subject& sub);
istream& operator>>(istream& is, Student& st);
int main()
try
{
ifstream ifs("Text.txt");
vector<Student>group;
Student s1, s2;
ifs >> s1;
group.push_back(s1);
getline(ifs, temp);
ifs >> s2;
group.push_back(s2);
cout << group.size();
cout << group[0].name;
cout << group[0].surname;
cout << group[1].name;
cout << group[0].my_marks[1].mark0;
}
catch (exception& e){
cerr << e.what() << endl;
return 1;
}
catch (...)
{
cerr << "exception n";
return 2;
}
istream& operator>>(istream& is, Subject& sub)
{
int m0, m1;
is >> m0;
if (!is) return is;
is>> m1;
sub.mark0 = m0;
sub.mark1 = m1;
return is;
}
istream& operator>>(istream& is, Student& st)
{
char n1[50];
char n2[50];
is >> n1;
is >> n2;
strcpy_s(st.name, n1);
strcpy_s(st.surname, n2);
if (!is) return is;
while (true)
{
Subject sub;
if (!(is >> sub)) break;
st.my_marks.push_back(sub);
}
return is;
}
我试过了,但还是一样的:
string temp
ifs >> s1;
getline(ifs, temp);
group.push_back(s1);
:
char n1[50];
char n2[50];
for (int i = 0;; ++i)
{
char n0;
is.get(n0);
if (isspace(n0)) break;
n1[i] = n0;
}
for (int i = 0;; ++i)
{
char n0;
is.get(n0);
if (isspace(n0)) break;
n2[i] = n0;
}
if (!is) return is;
strcpy_s(st.name, n1);
strcpy_s(st.surname, n2);
然后我在每个学生的名字后面加上':'
,并使用is.get(n1, 100, ':')
。它仍然正确读取第一行,但拒绝读取下一行。不管我做了什么,我都不能将文本光标移动到新行的开始。如果有人能帮助我,我将不胜感激。
第二个学生没有被读取,因为您将流置于读取第一个学生的坏状态。
if (!(is >> sub)) break;
你基本上读取主题,直到输入中断(也就是当你点击一个名字时)。由于您没有将流的状态重置为good
,因此任何进一步的读取尝试都将被忽略。
你有两个选择。
在阅读完受试者后将状态设置为good
这有一个问题,你可能会进入一个无限循环,因为你的检查流状态是不稳定的。读取一行,然后解析该行的主题信息。
我会选择选项2。
// After you have read the name.
// The rest of the line is scores. So read a whole line.
std::string line;
std::getline(is, line);
// convert the line into a stream.
std::stringstream linestream(line);
// Now parse the stream for subject.
Subject sub;
while(linestream >> sub) { // Note this reads an item and checks the
// state of the stream. The while body
// is only entered on a successful read.
st.my_marks.push_back(sub);
}
相关文章:
- 使用新行和不使用新行读取文件
- 遇到新行时,有没有办法停止istream_iterator
- PangoLayout 中忽略的新行
- 使用 clang 格式时,当行很大时,如何将右括号分成新行?
- 如何检测将文本文件读入 int 数组的新行
- 当 getline 直到新行才读取时会发生什么?
- 添加新行时工作代码引发异常.调试技巧?
- QTree查看新行,没有布局就不可见已更改
- 新行上的 clang 格式右括号
- C++流:保存到新行而不是覆盖旧行
- (C++) 使用诅咒打印从文件中读入的新行
- 按升序输出整数时,将最后一个整数放在新行上
- 用C++计算输入文本的新行数
- 为什么我的代码在终端中没有输出任何内容.开始新行没有错误
- WriteConsoleOutputCharacterW - 我的新行在哪里?
- 为什么当测试用例数为 1 时,我的程序不输入而是打印新行?
- 如何运行 while 循环直到到达新行?
- 在Visual Studio中调试:断点移动并插入新行
- 将文本光标移动到新行
- 在没有将光标移动到新行之前,在gotoxy(80,25)位置上写入字符