不知道如何表达这个问题,但我正在为一个作业编写一个程序,除了输入/输出之外,我们不允许使用预先存在的库。我们也只能使用原始数据类型。我必须阅读一个包含单词的文本文件,删除单词中的所有标点符号,然后将这些单词存储在2D字符数组中。
这个问题似乎是,当一个单词以非字母字符开头时,使用cout << stack[top]
时不会输出整个单词,但当我用cout << stack[top][i]
输出每个单独的字符时,它会产生预期的输出。
"stack"是一个2D数组,其中包含组成单词的字符。
"top"是表示堆栈长度的变量
代码:
#include <iostream>
#include <fstream>
using namespace std;
// Function Prototypes
void push(char word[]);
char formatCharacter(char letter);
bool isAlphabet(char letter);
char toLowercase(char letter);
// Global Variables
const int STACK_SIZE = 50000;
const int WORD_SIZE = 30;
char stack[STACK_SIZE][WORD_SIZE];
int top = 0;
int words = 0;
int wordCount[STACK_SIZE];
int main(){
// Local Variables
char filename[20];
ifstream fin;
char word[WORD_SIZE];
// Get file input
cerr << "Please enter the name of the input file: ";
cin >> filename;
// Open file
fin.open(filename);
// Print error if file doesn't open, then quit the program.
if (!fin) {
cerr << "Error opening file " << filename << ". Program will exit." << endl;
return 0;
}
// Read the file into the stack
while (fin >> word) {
push(word);
}
// Close file
fin.close();
}
void push(char word[]){
if (top == STACK_SIZE) return;
int i = 0;
int j = 0;
do {
if (isAlphabet(word[i])){
word[i] = formatCharacter(word[i]);
stack[top][i] = word[i];
cout << stack[top][i]; // Output fine
j++;
}
i++;
} while (word[i]);
wordCount[words] = j;
//cout << stack[top] << ": " << wordCount[words] << endl; // Output incorrect
cout << endl;
top++;
words++;
return;
}
bool isAlphabet(char letter){
if ((letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z')){
return false;
}
else{
return true;
}
}
char formatCharacter(char letter){
if ((letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z')){
letter = ' ';
}
else{
if (letter >= 'A' && letter <= 'Z'){
letter = toLowercase(letter);
}
}
return letter;
}
char toLowercase(char letter){
letter = letter + 32;
return letter;
}
isAlphabet((只是检查它是否是一个字母字符
formatCharacter((通过将字符替换为"\0"来删除任何标点符号,还将大写更改为小写。
输入:
Jabberwocky
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
使用cout << stack[top][i]
:时的输出
jabberwocky
twas
brillig
and
the
slithy
toves
did
gyre
and
gimble
in
the
wabe
all
mimsy
were
the
borogoves
and
the
mome
raths
outgrabe
使用cout << stack[top]
:时的输出
jabberwocky: 11
: 4
brillig: 7
and: 3
the: 3
slithy: 6
toves: 5
did: 3
gyre: 4
and: 3
gimble: 6
in: 2
the: 3
wabe: 4
all: 3
mimsy: 5
were: 4
the: 3
borogoves: 9
and: 3
the: 3
mome: 4
raths: 5
outgrabe: 8
注意"twas"这个词不见了。我宁愿不遍历每个单词的每个字符来获得我需要的输出。如果有任何建议,我将不胜感激,谢谢!
最简单的修复方法是更改:
stack[top][i] = word[i];
收件人:
stack[top][j] = word[i];
^ j not i here
这将确保'Twas
最终成为twas
而不是