读取字符并创建数组c++

Reading in characters and creating array c++

本文关键字:数组 c++ 创建 字符 读取      更新时间:2023-10-16

如何从文件中读取一行字符。首先,程序从文件中读取一个整数。该数字表示下一步要读入的字符数。接下来读取中的字符并将它们存储在一个数组中。那么,我该如何创建"char"变量,以便正确读取Michael的字符,并将其显示在数组中呢。

file.txt: 
8 
Michael

im使用inputFile>>integer,从那里我需要这个整数来制作这个数组char-mike[integrat];,然后我可以读取数组的字符

回答您的问题:

#include <fstream>
using namespace std;
int main() {
    ifstream f("file.txt");
    int n;
    f >> n;
    char chs = new char[n];
    for (int i = 0; i < n; ++i) f >> chs[i];
    // do something about chs
    delete [] chs;
}

但是,我会选择(如果你的Michael出现在它自己的线上(:

#include <fstream>
#include <string>
using namespace std;
int main() {
    ifstream f("file.txt");
    int n;
    f >> n;
    string str;
    getline(f, str);
}
#include <fstream.h>
#include <string.h>
int main() 

    {
        ifstream f("file.txt",ios::in);
        int n;
        f >> n;
        char string[n];
        f.getline(string,n);
       cout<<string;
    }

这将输出file.txt中的以下字符串。