将一系列字符串读取到char数组中

Reading a series of strings into a char array

本文关键字:char 数组 读取 一系列 字符串      更新时间:2023-10-16

这是程序的main()部分中的代码:

 int numFiles;
 cout << "How many signal files are there?";
 cin >> numFiles;
 char singalFiles[numFiles][100];
 string backgroundFile;
 for (int i=0;i<numFiles;i++){
    string singalFile;
    cout << "Please input the name of singal file" << i << ".";
    cin >> singalFile;
    singalFile >> char singalFiles[i][100];
    string backgroundFile;
    cout << "Please input the name of background file" << i << ".";
    cin >> singalFile;
    backgroundFile >> char backgroundFiles [i][100];
 }

这是我作为一个研究项目的一部分正在编写的代码。我想知道是否有人能帮我做这件事。我对c++很陌生,不知道如何将字符串写入char数组。

我在将字符串读取到char数组中以便将它们存储在那里时遇到了问题。也就是说,我试图将每个名为backgroundFile和signalFile的字符串读取到char数组backgroundFiles和singalFiles中。

定义char singalFiles[numFiles][100];可能是一个问题,因为标准C++要求数组的大小为常数。一些编译器接受这个作为扩展,但你不应该依赖它

但作为一个简单的替代方案,您可以使用向量和字符串:

vector<string> singalFiles(numFiles);  

然后你可以很容易地读取数据:

   //cin >> singalFile;   ==> combine with the next line
   // singalFile >> char singalFiles[i][100];
   cin >> singalFiles[i];

你甚至不需要提前预订尺码。你也可以这样做:

vector<string> singalFiles;  // the size of a vector is dynamic anyway !   
... 
cin >> singalFile;  // as you did before
signalFiles.push_back(signalFile);  // add a new element to the end of the vector.