这是程序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。
答案 0 :(得分:0)
定义char singalFiles[numFiles][100];
可能是一个问题,因为标准C ++要求数组的大小是常量。有些编译器接受这个作为扩展,但你不应该依赖它。
但作为简单的替代方案,您可以使用vectors和字符串:
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.