Trying to pick out all of the "-" signs in a string.

I am letting the user input a sentence(telling them to put in - signs). I want the program to count how many the user puts in. For some reason, the program keeps saying 0(no matter how many "-" I put in the sentence. What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

using namespace std;

int main()
{
    char sent[100];

    cout << "Enter a sentence with a lot of '-' in it: ";
    cin >> sent[100];
    char minussign = '-';
    int count = 0;

    for (int i=0; i<100;i++)
       {
        if (sent[i] == minussign)
            count++;
       }

    cout << count;

    return 0;
}
Last edited on
try changing this char minussign = '-'; into this: char minussign = 45; (ASCII characters)
Your mistake is at
cin >> sent[100];

That means you are putting whatever the user enters, into the 100th element in the array (which is a really bad idea in this case, as sent stops at 99).

Change it to cin >> sent to have the input entered into the entire array instead and it should work correctly.
Last edited on
Hmm. It still returns 0. Any other ideas?

Also, when do you know to use the ASCII characters vs using what I did?
well i remembered me using ascii characters for something like this but as james already said the solution is changing it to cin >> sent; instead of cin >> sent[100];. code works with either'-' or 45 it doesn't matter
Last edited on
James, I thought that would work! But it still returns 0...
You should use getline.
http://www.cplusplus.com/reference/string/getline/

Otherwise, you will only catch the first word.
I just tried that, but it is giving me an error


 no matching function for call to 'getline(std::istream&, char&)'


after I put in getline (cin, sent);

I think maybe because it is not a string?
You should use cin's version of getline in this case, if you don't want to use strings.

http://www.cplusplus.com/reference/iostream/istream/getline/
cin.getline(sent, 100);
Last edited on
Ahhh that worked! Thank you! I didn't know that that existed.

So any time I want to loop through each character of string, I must use getline?
Every time you want to catch more than one word, you must use getline.
Topic archived. No new replies allowed.