Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,557 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,613 people online right now. Registration is fast and FREE... Join Now!




Help with user input string.

 
Reply to this topicStart new topic

Help with user input string.

gator6688
30 Oct, 2007 - 02:03 PM
Post #1

D.I.C Head
**

Joined: 23 Sep, 2007
Posts: 84


My Contributions
I have to make a program that reads a sentence, one character at a time, from the keyboard into a string class object. The entry will terminate with a (.). Then I have to search the array to determine how many times a particular character, specified by the user, occurs in the sentence. Am I on the right track?

CODE
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string str;
    char ch1=0, i;

    cout << "Enter a sentence: ";
    getline(cin,str,'.');

    cout << "Enter a character you would like counted: \n";
    cin  >> ch1
    for(i=0;i<str.length(); i++)
    {
    return 0;
}


User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Help With User Input String.
30 Oct, 2007 - 02:24 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
All you need to do is loop through the characters in the string. Remember each character is nothing but an array of characters. Compare each one with the character that the user entered. Here is the product...

CODE

int count = 0;

for(i=0;i < (int)str.length(); i++)
{

    // If the character in the string equals the user's character, increment the count.
    if (str[i] == ch1) { count++; }
}

// Print out the total number of characters found
cout << "Total number is: " << count << endl;


That is all there is to it. Oh and don't forget the semicolon after the line cin >> ch1;.

Enjoy!

"At DIC we be coding ninjas!" decap.gif
User is offlineProfile CardPM
+Quote Post

gator6688
RE: Help With User Input String.
30 Oct, 2007 - 03:09 PM
Post #3

D.I.C Head
**

Joined: 23 Sep, 2007
Posts: 84


My Contributions
Thank You for your help!
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/7/09 10:03PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month