c++将.txt文件中的字符串添加到字符串数组中,并显示数组的值
c++ add string from .txt file into string array and display the value of the array
我有一个包含以下内容的文件:tdogicatzhpigu
和另一个包含下列内容的文件
dog
pig
cat
rat
fox
cow
在单独的线路上。
下面的代码显示了我在一个do-while循环菜单中执行此操作的尝试。
if (selection == 1) {
//Gets the characters from the textfile and creates an array of characters.
fstream fin1("text1.txt", fstream::in);
if (fin1.is_open())
{
cout << "text1.txt successfully added to an array" << endl;
while (!fin1.eof()) {
if (!fin1.eof()) {
for (int i = 0; i < 14; i++) {
for (int e = 0; e < 14; e++) {
fin1 >> chArray[i][e];
}
}
}
}
}
else if (!fin1.is_open())
{
cout << "ERROR: ";
cout << "Can't open text1.txt filen";
}
fin1.close();
//Get the string values from the file and add into an array of strings
fstream fin2("search1.txt", fstream::in);
if (fin2.is_open()) {
cout << "Search1.txt successfully added to an array" << endl;
cout << "------------------------------------------------------------------------" << endl;
while (!fin2.eof()) {
if (!fin2.eof()) {
for (int j = 0; j <= 6; ++j) {
getline(fin2, wordsArray[j]);
}
}
}
}
现在,如果我打印选择1中的数组,它会正确显示两者,一切都很好,但是在下面的选择2中,我试图再次显示chArray的内容,但由于某种原因,它错过了"t"
:
else if (selection == 2) {
for (int i = 0; i < 14; i++) {
cout << chArray[0][i] << endl;
}
选择3,尝试显示单词数组,什么都不显示,这是选择3的代码:
else if (selection == 3) {
for (int j = 0; j <= 6; ++j) {
cout << wordsArray[j] << endl;
}
试试这个(我只写了你应该做的更改,所以保持其他代码原样):
string chArray;
string wordsArray[6];
do
{
....//other code
if (selection == 1)
{
if (fin1.is_open())
{
cout << "text1.txt successfully added to an array" << endl;
if(!getline(fin1,chArray))//read the whole line from the file into the string
//show error message that a file was not read successfully
}
.....
for (int j = 0; j < 6; ++j)//change j<=6 to j<6 since your array has 6 elements
.....
}
else if (selection == 2)
{
for (int i = 0; i < 14; i++)
cout << chArray[i] << endl;//no need to access this as two dimensional array
.....
}
else if (selection == 3)
{
for (int j = 0; j < 6; ++j)//change j<=6 to j<6 since your array has 6 elements
....
}
}while(selection != your exit value);
希望这能有所帮助。
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13