如何读取文本文件的第2行、第3行和第4行。C++; 我试图读取C++中的文本文件的每一行。我让它在文本文件的第一行工作,但是我如何读取其他行呢?另外,我是C++超级NoOB,请不要烤我。< /P>
代码:如何读取文本文件的第2行、第3行和第4行。C++; 我试图读取C++中的文本文件的每一行。我让它在文本文件的第一行工作,但是我如何读取其他行呢?另外,我是C++超级NoOB,请不要烤我。< /P>,c++,file-io,ifstream,C++,File Io,Ifstream,代码: void品位::readInput() { ifstream infle(“Grades.txt”); if(infle.good()) { 弦线; getline(填充、sLine); cout我会给你一些提示-这可能更像是现在 我推荐 将读数与打印分开 将分数视为数字(例如,int或double),这样您就可以实际使用它们,并进行一些验证,以确保您没有阅读无意义的内容 使用惯用循环,而不仅仅是if(infle.good())——例如,在尝试读取之前,您无法判断是否已到达文件末尾
void品位::readInput()
{
ifstream infle(“Grades.txt”);
if(infle.good())
{
弦线;
getline(填充、sLine);
cout我会给你一些提示-这可能更像是现在
我推荐
- 将读数与打印分开
- 将分数视为数字(例如,
int
或double
),这样您就可以实际使用它们,并进行一些验证,以确保您没有阅读无意义的内容
- 使用惯用循环,而不仅仅是
if(infle.good())
——例如,在尝试读取之前,您无法判断是否已到达文件末尾
修复界面,我建议这样做
struct Grade {
void readInput(std::string fname);
void print(std::ostream& os = std::cout) const;
private:
static constexpr auto max_line_length = std::numeric_limits<ssize_t>::max();
std::vector<int> grades;
};
这将是主要节目
readGrades
的简化/扩展版本可以是:
void Grade::readInput(std::string fname) {
std::ifstream infile(fname);
infile.ignore(max_line_length, '\n'); // ignore the first line
int grade = 0;
while (infile >> grade) {
grades.push_back(grade);
infile.ignore(max_line_length, '\n'); // ignore rest eating newline
}
}
注意我们如何忽略我们不感兴趣的线条或部分。为了额外的控制,考虑禁用空格跳转:
infile >> std::nowskipws;
打印功能可以是一个简单的:
void Grade::print(std::ostream& os) const {
os << "Grades:";
for (int g : grades) {
os << " " << g;
}
os << std::endl;
}
给定grades.txt
:
Ignore the first line
12
17
1
29
一个简单的版本:
std::string line1;
std::string line2;
std::string line3;
std::string line4;
std::getline(infile, line1);
std::getline(infile, line2);
std::getline(infile, line3);
std::getline(infile, line4);
使用循环:
static const unsigned int LINES_TO_READ = 3;
std::string line1_ignored;
std::getline(infile, line1_ignored);
for (unsigned int i = 0; (i < LINES_TO_READ); ++i)
{
std::string text_line;
if (std::getline(infile, text_line))
{
std::cout << text_line << std::endl;
}
else
{
break;
}
}
static const unsigned int line_TO_READ=3;
std::字符串行1_被忽略;
std::getline(填充,忽略第1行);
for(无符号整数i=0;(i Std::CUT使用<代码>而<代码>循环,而不是<代码>如果 1。“我在文本文件中的第一行工作,但是我怎么读其他的呢?”“你尝试过使用循环吗?考虑从2中学习”为什么这个问题被标记,如果很明显不是C?超级NoOB排名上升。谢谢Johnny Mopp。
Grades: 12 17 1 29
Ignore the first line
12
17
1
29
std::string line1;
std::string line2;
std::string line3;
std::string line4;
std::getline(infile, line1);
std::getline(infile, line2);
std::getline(infile, line3);
std::getline(infile, line4);
static const unsigned int LINES_TO_READ = 3;
std::string line1_ignored;
std::getline(infile, line1_ignored);
for (unsigned int i = 0; (i < LINES_TO_READ); ++i)
{
std::string text_line;
if (std::getline(infile, text_line))
{
std::cout << text_line << std::endl;
}
else
{
break;
}
}