逐字符使用fstream进行读取,并将fstream传递给函数进行进一步读取

Reading using fstream character by character and passing the fstream to a function for further reading?

本文关键字:fstream 读取 函数 进一步 并将 字符      更新时间:2023-10-16

好的,所以我试图打开一个文件进行读取,我只想读取第一个字符,然后根据该字符的内容将其发送给给定的函数。例如,如果它是一个数字,我会将它发送给一个函数,该函数会继续读取,看看它只是一个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();
}