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. 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.
Also as Bartosz-Marcinkowski suggested, use a vector. You'll still be able to access each character, just use it as a 2D array.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.