简体   繁体   中英

Reading “tokens” from a string line in C++ I/O

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.

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM