查找文件末尾时出现问题
Issue with finding the end of a file?
从文件中读取输入时出现问题,计算每个单词中的字符数,然后将此计数输出到输出文件。
输入文件中的示例内容:一二三四五
正确的输出是:3 3 5 4 4
现在,如果在输入文件中我在"五"的末尾放置一个空格,则下面的代码可以工作。 如果我不放置这个空格,代码就会卡在嵌入的 while 循环中(见下文)。
有什么想法吗? 提前谢谢。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c; //declare variable c of type char
int count = 0; //declar variable count of type int and initializes to 0
ifstream infile( "input.txt" ); //opens file input.txt for reading
ofstream outfile( "output.txt" ); //opens file output.txt for writing
c = infile.get(); //gets first character from infile and assigns to variable c
//while the end of file is not reached
while ( !infile.eof() )
{
//while loop that counts the number of characters until a space is found
while( c != ' ' ) //THIS IS THE WHILE LOOP WHERE IT GETS STUCK
{
count++; //increments counter
c = infile.get(); //gets next character
}
c = infile.get(); //gets next character
outfile << count << " "; //writes space to output.txt
count = 0; //reset counter
}
//closes files
infile.close();
outfile.close();
return 0;
}
解决此问题的另一种方法是简化:
#include <fstream>
#include <string>
int main()
{
std::string word;
std::ifstream infile("input.txt");
std::ofstream outfile("output.txt");
while (infile >> word)
outfile << word.size() << ' ';
}
修改内部的条件,同时:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c; //declare variable c of type char
int count = 0; //declar variable count of type int and initializes to 0
ifstream infile( "input.txt" ); //opens file input.txt for reading
ofstream outfile( "output.txt" ); //opens file output.txt for writing
c = infile.get(); //gets first character from infile and assigns to variable c
//while the end of file is not reached
while ( !infile.eof() )
{
//while loop that counts the number of characters until a space is found
while( c != ' ' && !infile.eof() )
{
count++; //increments counter
c = infile.get(); //gets next character
}
c = infile.get(); //gets next character
outfile << count << " "; //writes space to output.txt
count = 0; //reset counter
}
//closes files
infile.close();
outfile.close();
return 0;
}
通过将字符检查为:
while(fgetc(infile) != EOF){
//Rest code goes here
}
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 编译要在英特尔Hyperscan中使用的.cc文件时出现问题
- 使用 seekg() 读取C++中的文件时出现问题
- sqlite3 和生成文件中的链接出现问题
- C++头文件和类实现出现问题
- 用户输入字符串的文件附加问题..C++
- node-gyp 的先有鸡还是先有蛋的问题:指向依赖项中的头文件
- 读取文件并将其存储在unordered_map中时出现问题
- 编译 llvm 插件时出现问题:llvm/Config/llvm-config.h:没有这样的文件或目录
- 我在使用C++文件时遇到了一些问题
- 在Linux上使用Clang / OLLVM交叉编译helloworld Windows可执行文件时的问题
- 将文件复制到自定义位置,存在字符串转换问题
- DirectX12 的问题:"d3dApp.h":没有这样的文件或目录
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 读取制表符分隔的文件时出现问题 C++
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 使用 RapidXML 解析大型 XML(大小大于 65 KB)文件时出现问题
- C++:读取.BMP文件时出现问题;文件结束时间早于预期