逐字符使用fstream进行读取,并将fstream传递给函数进行进一步读取
Reading using fstream character by character and passing the fstream to a function for further reading?
好的,所以我试图打开一个文件进行读取,我只想读取第一个字符,然后根据该字符的内容将其发送给给定的函数。例如,如果它是一个数字,我会将它发送给一个函数,该函数会继续读取,看看它只是一个int还是一个float。我似乎不知道怎么做这个
void dummy(char dum, std::ifstream& fin){
char test = dum;
fin>>test;
string simple = simple + test;
simple = simple + test;
ofstream outFile;
outFile.open("output.txt");
outFile<<simple<<"n";
return;
}
int main(int argc, char *argv[]){
char c;
//ifstream readFile;
/*if(argc >= 1){
readFile.open(argv[1]);
}*/
ifstream readFile;
readFile.open("input.txt");
readFile.unsetf(ios_base::skipws);
readFile>>c;
while(!readFile.eof())
{
switch(c){
case 'a':
dummy(a,readFile);
}
}
}
它一直在内存位置(location)抛出以下错误:Microsoft C++异常:std::bad_alloc。非常感谢您的帮助。
错误是由以下行引起的:
string simple = simple + test;
以前从未见过这种情况,但我猜你正在连接一个尚未初始化的字符串。使用这个替代:
void dummy(char dum, std::ifstream& fin)
{
char test = dum;
fin>>test;
string simple;
simple = simple + test;
ofstream outFile;
outFile.open("output.txt");
outFile<<simple<<"n";
return;
}
编辑:要从文本文件中读取一定数量的字符,请使用istream::read方法:
char test = ' ';
fin.read( &test, 1 ); // read one character into buffer
您可以打开您的txt文件,并通过下面的代码给出第一个字符!第一个字符在变量s中。
#include <fstream>
#include <iostream>
#include <conio.h>
using namespace std;
void main (void)
{
char *s=NULL;
char str1;
ifstream file_txt("file_name.txt");
if (!file_txt)
{
cout << "sorry I cannot find txt file! ";
getch();
exit(0);
}
file_txt >> str1;
s= &str1;
file_txt.close();
}
相关文章:
- 如何在 c++ 中使用 fstream 读取.txt文件
- 使用 fstream 读取 csv,并且只阅读 fstream
- 使用 fstream 读取文件后,我无法立即写入文件
- CMD窗口停止工作,文本文件使用fstream读取错误
- 使用C 中的Fstream读取和附加文件
- 使用Fstream读取二进制文件
- 使用 fstream 读取
- 通过fstream读取文件时,存储在变量中的损坏数据..为什么?
- 如何使用fstream读取文件的特定行
- C++:通过fstream读取txt文件
- 使用 fstream 读取选定的列
- C++ 使用 fstream 读取文件
- FStream读取txt文件
- 使用相同的fstream读取和写入相同的文件
- 我无法使用 fstream 读取.dat文件
- 从fstream读取输入
- c++中使用fstream读取对象
- 使用fstream读取完整文件到字符串的最佳方式
- 在DLL中使用fstream读取文件的问题
- c++ fstream读取utf-8字符集