如何将 .txt 文件中的单词复制到数组中。然后在单独的行上打印每个单词
How to copy words from .txt file into an array. Then print each word on a separate line
目标是从名为 "words.txt" 的文件中读取一组字符串,并将每个单词保存到数组字符串中。但是,我无法将单词保存并打印到控制台。我认为问题出在我的 GetStrings 函数中,但我不知道为什么。调用 PrintStrings 函数时,控制台不会打印任何内容。这让我觉得要么什么都没有保存到数组中,要么打印函数不正确。
int main ()
{
int count = 0;
string strings [MAXSTRINGS];
GetStrings(strings);
// cout << strings[1];
PrintStrings(strings, count);
return 0;
}
int GetStrings (string S [])
{
ifstream input ("words.txt");
int count = 0;
while (input >> S[count])
{
count++;
}
input.close ();
return 0;
}
void PrintStrings (string S [], int C)
{
int w = 0;
while (w < C)
{
cout << S[w] << endl;
w++;
}
}
问题是局部变量。在函数内部声明的变量不能被其他函数使用:
int GetStrings (string S [])
{
ifstream input ("words.txt");
/* --> */ int count = 0;
这里是使用它的地方:
PrintStrings(strings, count);
函数 GetStrings
中的变量 count
与 main
中的变量不同。
如果您希望函数修改外部(函数)变量,请通过引用传递它:
int GetStrings (string S [], int& count)
我建议将数组换成 std::vector
。 std::vector
保持其计数,您可以使用 std::vector::size()
访问它。
目标是从名为 "words.txt" 的文件中读取一组字符串,并将每个单词保存到数组字符串中。但是,我无法将单词保存并打印到控制台。我认为问题出在我的 GetStrings 函数中,但我不知道为什么。调用 PrintStrings 函数时,控制台不会打印任何内容。这让我觉得要么什么都没有保存到数组中,要么打印函数不正确。
int main ()
{
int count = 0;
string strings [MAXSTRINGS];
GetStrings(strings);
// cout << strings[1];
PrintStrings(strings, count);
return 0;
}
int GetStrings (string S [])
{
ifstream input ("words.txt");
int count = 0;
while (input >> S[count])
{
count++;
}
input.close ();
return 0;
}
void PrintStrings (string S [], int C)
{
int w = 0;
while (w < C)
{
cout << S[w] << endl;
w++;
}
}
问题是局部变量。在函数内部声明的变量不能被其他函数使用:
int GetStrings (string S [])
{
ifstream input ("words.txt");
/* --> */ int count = 0;
这里是使用它的地方:
PrintStrings(strings, count);
函数 GetStrings
中的变量 count
与 main
中的变量不同。
如果您希望函数修改外部(函数)变量,请通过引用传递它:
int GetStrings (string S [], int& count)
我建议将数组换成 std::vector
。 std::vector
保持其计数,您可以使用 std::vector::size()
访问它。