Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote a program that reads a file, saves in a vector of string the words:
2
C++
int main()
{
	string parole[1000];
	string parola;
   int conteggio = 0;
   int n=0;
ifstream infile("C:\\Users\\Mio\\Desktop\\ciao.txt");
   if (!infile.good()){
      cout << "errore apertura file" << endl;
      return 0;
   }
   while ( infile >> parola )
    {
      parole[n]=parola;
      cout << parole[n]<<endl;
      n++;
   }  
      
  return 0;
}


I wrote:
string parole[1000];

but I don't know the lenght of parole, how can I write?

What I have tried:

maybe I must use pointer? I don't know how I can solve
Posted
Updated 25-Oct-19 11:28am
v3

Try
C++
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  vector <string> vw;

  for(;;)
  {
    string word;
    cin >> word;
    if ( ! cin ) break;
    vw.push_back(word);
  }

  for (const auto & w : vw)
    cout << w << endl;

  cout << "no. oof words: " << vw.size() << endl;
}
To get the input from your text file, redirect the standard in, e.g.
showwords.exe < C:\Users\Mio\Desktop\ciao.txt

(assuming showwords.exe is the name of the executable).
 
Share this answer
 
Comments
Member 14594285 28-Oct-19 3:24am    
what is "w"? when you write:
const auto & w : vw
CPallini 28-Oct-19 3:57am    
w is a word (a string, because vw is a vector<string>). See
https://en.cppreference.com/w/cpp/language/range-for
Your arent you a vector but a fixed array. Read this vector tutorial.

Your parole is a string. This class has a length() function.

tip: use a search machine and read the documentation ;-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900