Reputation:
I am wondering how I can do the following in C++ since I am only familiar with Java.
I have a string which we will call line. string line = "hello how are you";
In C++ I have retrieved that line from getLine(). I want to traverse through this line so I can count the number of words in this line. The result should be 4, in my example.
In Java, I would have imported Scanner. Then do something like this:
//Other scanner called fileName over the file
while(fileName.hasNextLine()) {
line = fileName.nextLine();
Scanner sc = new Scanner(line);
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
}
I am only using #include<iostream>, fstream and string.
Upvotes: 1
Views: 4397
Reputation: 1854
I would avoid ifstream::getline
and just use ifstream::get
instead. You don't even need to use string
.
#include <iostream>
int main()
{
int numwords = 1; //starts at 1 because there will be (numspaces - 1) words.
char character;
std::ifstream file("readfrom.txt");
if (file.fail())
{
std::cout << "Failed to open file!" << std::endl;
std::cin.get();
return 0;
}
while (!file.eof())
{
file >> character;
if (character == ' ')
{
numwords++;
std::cout << std::endl;
}
else if (character == '\n') //endline code
{
std::cout << "End of line" << std::endl;
break;
}
else
std::cout << character;
}
std::cout << "Line contained " << numwords << " words." << std::endl;
std::cin.get(); //pause
return 0;
}
Upvotes: -1
Reputation: 502
You can use stringstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin,line);
stringstream ss(line);
string word;
int count=0;
while(ss>>word){//ss is used more like cin
count++;
}
cout<<count<<endl;
return 0;
}
Upvotes: 4