C++:一次阅读一个字符,直到一行的末尾不起作用
C++: Reading in one character at a time until the end of a line not working
我应该一次读取一个文本文件一个字符,每次有新行时,line
应该增加一个。
所以这是代码的相关部分:
ifstream textFile.open("PATHWAY::HERE//RRER.txt");
int line = 1;
char letter;
while (textFile)
{
//Read in letter
textFile >> letter;
// If you reach the end of the line
if (letter == 'n')
{
line++;
cout << line;
}
}
由于某种原因,if 语句被完全忽略,并且永远不会打印出行。
尽管答案(到目前为止)已经正确提到了有关""的问题,但提到的方法可能不起作用。>>
的原因是格式化的输入运算符将跳过空格。您必须使用std::ifstream::get
读取文件
代码将如下所示:
while (textfile.get(letter))
{
// If you reach the end of the line
if (letter == 'n')
{
line++;
cout << line;
}
}
代码中存在一些错误:
- 它是""
- 而不是"/n"
- 行 = 0 而不是 1
您需要使用
std::ifstream::get
来读取文件删除
textFile>> letter;
,因为它将跳过whitespaces
所以你的代码将如下所示
ifstream textFile.open("PATHWAY::HERE//RRER.txt");
int line = 0; // not 1
char letter;
while(textFile.get(letter))
{
// If you reach the end of the line
if (letter == 'n')
{
line++;
cout << line;
}
}
您可以使用
n
字符来查找这是否是换行符
所以你的代码应该是
ifstream textFile.open("PATHWAY::HERE//RRER.txt");
int line = 1;
char letter;
while (textFile)
{
// Read in letter
textFile>> letter;
// If you reach the end of the line
if (letter == 'n')
{
line++;
cout << line;
}
}
使用 istream::get
ifstream textFile.open("PATHWAY::HERE//RRER.txt");
int line = 0;
char letter;
while(textFile.get(letter))
{
// If you reach the end of the line
if (letter == '/n')
{
line++;
cout << line;
}
}
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++:一次阅读一个字符,直到一行的末尾不起作用
- 在C++中读取一行之后的行不起作用
- 关于指针和重载的问题(.append() 在一行中不起作用)