【发布时间】:2016-10-12 21:38:33
【问题描述】:
所以我一直在网上寻找一种读取字符后跟数字的方法,到目前为止,每个人都在使用字符串函数。但是,我只被允许使用 C 风格的字符数组,当我读入文件时,我的程序遇到了问题。
我的文本文件是这样的:
23
11
Java 2 linux 3 fear 0 pool 2 do 0 red 1 lock. 1 I 0 random 2 computers, 0 not 0 the 0 open 2 car! 2 C, 0 lack 0 of 0 dog 1 green 2 C++ 0 bottle 2 wrong, 2 them. 0
5 1 10 21 9 6 21 11 13 16 20
到目前为止我的程序打印出来了:
11 23
Java 2
但是,我希望它打印出所有内容。有什么建议吗?这是我的代码
#include <iostream>
#include <fstream>
using namespace std;
struct pieces {
char word[5];
int jump;
} ;
// Main Function
int main ()
{
// declare variables
int wordCount[2];
int keyCount[2];
int numKeys;
int numWords;
int keyAmount = 1;
int wordAmount = 23;
pieces cypher[wordAmount];
char filename[10];
ifstream inData;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
inData.open(filename);
if(inData.is_open());
{
// read list of names into array
for ( numKeys = numWords = 0; numKeys < keyAmount; numKeys++){
inData >> wordCount[numKeys] >> keyCount[numKeys];
for( numWords = 0; numWords < wordAmount; numWords++){
inData >> cypher[numWords].word >> cypher[numWords].jump;
}
}
// print out unsorted onto console
for ( int i = 0; i < numKeys; ++i){
cout << wordCount[i] << " ";
cout << keyCount[i] << "\n";
cout << cypher[i].word << " ";
cout << cypher[i].jump << " ";
}
}
inData.close();
return 0;
}
【问题讨论】:
-
使用动态调整大小的字符数组创建自己的
string类可能更简单,然后使用使用string的解决方案之一 -
你从哪里得到 keymount = 1?
-
@AndyG 那么我是否会在每次阅读单词时创建一个动态调整大小的字符数组?
-
@Raindrop7 如果我将该数字更改为其他任何数字,它只会继续打印数字,甚至不会打印一个字符。
-
您想将单词存储在一个数组中,将数字存储在另一个数组中吗?