Question:

Need Help with C++ code?

by  |  earlier

0 LIKES UnLike

I have written this code to enter a string and then count the number of a user input character. For example you enter a string and then it ask to input a chacater to count the number of occurances that chacater appears in the string. My code only returns a value of 1.

the code;

#include <iostream>

#include <string>

using namespace std;

int main()

{

string message;

int i = 0, letter;

int cnt = 0;

cout << "Enter String: \n";

getline(cin, message, '\n');

cout << "\nEnter a letter to count in he string: " << endl;

cin >> letter;

unsigned pos = message.find(letter, 0);

while ( pos != string::npos ) {

cnt++;

pos = message.find(letter, pos);

}

cout << "character occurred " << cnt << " times.\n" << endl;

return 0;

}

 Tags:

   Report

1 ANSWERS


  1. I&#039;m not familiar with the string type but I find the following line a little suspect:

    while ( pos != string::npos ) {

    I think you&#039;re expecting to compare pos to the last character ordinal of the string, but how can string::npos relate to a specific instance, message?

    Hope that helps.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.