[英]How to copy words from .txt file into an array. Then print each word on a separate line
The goal is to read a set of strings from a file called "words.txt" and save each word into the array strings. 目的是从名为“ words.txt”的文件中读取一组字符串,并将每个单词保存到数组字符串中。 However I am have trouble saving and printing the words to the console. 但是我在保存单词并将其打印到控制台时遇到了麻烦。 I think the problem is within my GetStrings function but I can't figure out why. 我认为问题出在我的GetStrings函数内,但我不知道为什么。 Nothing prints out to the console when the PrintStrings function is called. 调用PrintStrings函数时,没有任何内容输出到控制台。 Which makes me think that either nothing is being saved into the array or the print function is not correct. 这使我认为要么什么都没有保存到数组中,要么打印功能不正确。
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++;
}
}
The problem is local variables. 问题是局部变量。 Variables declared inside functions cannot be used by other functions: 在函数内部声明的变量不能被其他函数使用:
int GetStrings (string S [])
{
ifstream input ("words.txt");
/* --> */ int count = 0;
Here's where it's used: 这是使用的地方:
PrintStrings(strings, count);
The variable count
inside the function GetStrings
is a different variable than the one in main
. 函数GetStrings
的变量count
与main
的变量count
不同。
If you want a function to modify an external (to the function) variable, pass it by reference: 如果您希望函数修改外部变量(对该函数),请通过引用将其传递:
int GetStrings (string S [], int& count)
I recommend exchanging the array for std::vector
. 我建议将数组std::vector
为std::vector
。 The std::vector
maintains its count and you can access it by using std::vector::size()
. std::vector
保持其计数,您可以使用std::vector::size()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.