[英]Reading a list of words, char by char from a file and storing them in an array
I am reading from a file which has words like: 我正在从一个文件中读取,该文件包含以下内容:
"connecting", "classes", "feeds".. “连接中”,“类”,“提要”。
I need to convert each character to lowercase and then call a function to remove suffix from each word. 我需要将每个字符转换为小写,然后调用一个函数来删除每个单词的后缀。 Say, first on connecting, then on classes...
说,首先是连接,然后是课堂...
I am done with rest of the part but have a problem reading the file and storing words in array. 我已经完成了剩下的部分,但是在读取文件并将单词存储在数组中时遇到了问题。
I will have a minimum of 50 such words in the file. 我在文件中至少要包含50个这样的单词。 What is the best way to store it?
最好的存储方式是什么?
{
int val=0; char fin_char;
string line;string arr[100];
ifstream myfile("testfile.txt");
if (myfile.is_open())
{
while(myfile.good())
{
getline(myfile,line);
arr[i]=line;
i++;
}
myfile.close();
for (int j=0;j<i;j++)
{
while (arr[j][k]!='\0')
{
c=arr[j][k];
cout<<"C"<<c<<" "<<"J:"<<" "<<j<<"K:"<<k<<"\n";
val=int(c);
if (val>=65&&val<=90){ val=val+32;fin_char=static_cast<char>(val);arr[j][k]=fin_char;}
k++;
}
}
for (int j=0;j<i-1;j++)
{
cout<<" "<<arr[j]<<"\n";
}
system("pause");
return 0;
}
This is the output I get: 这是我得到的输出:
C99 J:0 K:0 C111 J:0 K:1 C110 J:0 K:2 C110 J:0 K:3
如果您想要一个随机访问的容器(如数组)而不声明其大小,请使用STL中的vector。
How are you storing the words in your text file ? 您如何将单词存储在文本文件中? Because unless each word is in a new line, your
arr
array would have only one element with a very long string. 因为除非每个单词都换行,否则您的
arr
数组将只有一个元素且字符串很长。
Also as Bartosz-Marcinkowski suggested, use a vector. 同样如Bartosz-Marcinkowski建议的那样,使用向量。 You'll still be able to access each character, just use it as a 2D array.
您仍然可以访问每个字符,只需将其用作2D数组即可。
If you need all the words in one line in the text file then i suggest splitting the line up based on spaces, you can use this function if you'd like : 如果您需要文本文件中一行中的所有单词,那么我建议根据空格将行分开,如果您愿意,可以使用此功能:
#include "sstream"
#include "vector"
#include "string"
vector<string> split(const string str)
{
stringstream ss(str);
string buf;
vector<string> elems;
while(ss >> buf)
elems.push_back(buf);
return elems;
}
which returns a vector of all the words in one line. 返回一行中所有单词的向量。 So, you can use it like this :
因此,您可以像这样使用它:
int main()
{
string line,
vector<string> arr;
ifstream myfile("testfile.txt");
if(myfile.is_open())
getline(myfile,line);
arr = split(line);
}
now if you wanted to access the 3rd character in the 5th word you would just need to arr[4][2]
现在,如果您想访问第5个字中的第3个字符,
arr[4][2]
需要arr[4][2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.