1

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.

1
  • Possible duplication of this link. Commented Jan 15, 2014 at 18:47

2 Answers 2

4

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; } 

http://ideone.com/Yl25KT

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I figured to just temporarily store the words in a string variable as I read through and update count. Before, I didn't realize cin was going to ignore white space. Thanks again, Ali.
-1

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; } 

1 Comment

Don't use eof() to control your loops reading from a stream! It doesn't work. Also, you need to check after reading whether the read was successful. Also note that your code doesn't cound the number of words but the number of spaces. You'd need to use std::unique() before doing so to make sure you don't have multiple spaces between two words.