将一系列字符串读入 char 数组
Reading a series of strings into a char array
这是程序 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++ 要求数组的大小是常量。一些编译器接受它作为扩展,但你不应该依赖它。
但作为简单的替代方法,您可以使用 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.
这是程序 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++ 要求数组的大小是常量。一些编译器接受它作为扩展,但你不应该依赖它。
但作为简单的替代方法,您可以使用 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.