string

what is the problem with this code??i want 2 find the space??


#include<iostream>
#include<string>

using namespace std;

int main(){
int c[5],space[5];

string name[5];

for(int i=0;i<5;i++){
cout<<"Enter Name :";
getline(cin,name[i]);

}

c[5]=0;
for (int i=0;i<5;i++){

c[i]=name[i].size();
cout <<endl << "name " << c[i] ;
}



space[5]=0;
for(int i=0;i<c[5];i++){
if(name[i] == ' '){
space[i]=i;
}
cout << endl << "total space" << space[i];
}
}


Do not Double post, Follow my very simple instructions please. http://www.cplusplus.com/forum/beginner/161842/
i couldnt get my ans??that why i m
Some people are just unreal... Jeezus christ.
closed account (2LzbRXSz)
Rahul, you just gotta be patient. And don't treat the people on this site like tools. We're people too.

Now, what exactly IS your problem with this code? Other than
if(name[i] == ' ')
Which, in my compiler doesn't compile and needs to be changed to
if(name[i] == " ")

What are you trying to accomplish? What spaces are you talking about??
So you have an array for strings, for size of strings, and for number of spaces in strings? For finding characters in strings look at std::string::find_first_of()
When posting code, please put it in code tags so we can refer to line numbers. Just highlight the code and click the "<>" button to the right of the edit window. Here is your code with tags and indentation:
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
26
27
28
29
30
31
32
33
#include<iostream>
#include<string>

using namespace std;

int
main()
{
    int c[5], space[5];

    string name[5];

    for (int i = 0; i < 5; i++) {
        cout << "Enter Name :";
        getline(cin, name[i]);

    }

    c[5] = 0;
    for (int i = 0; i < 5; i++) {

        c[i] = name[i].size();
        cout << endl << "name " << c[i];
    }

    space[5] = 0;
    for (int i = 0; i < c[5]; i++) {
        if (name[i] == ' ') {
            space[i] = i;
        }
        cout << endl << "total space" << space[i];
    }
}

Delete line 19. You don't need it and it causes undefined behavior because c[5] is out of bounds. Remember, C++ arrays are indexed starting at 0, so if there are 5 items then they are numbered 0-4.

Line 28 is illegal.

What is your expected output? Are you trying to count the number of spaces in each string? Or just print whether the strings contains a space?
dear all i want 2 find the space position in my arrayy??plz give me a solution to wriie this code....
question is" take 5 names from user and find the space postion in the array??
Use string::find_first_of() to look for a space. It returns the position of the space, or string::npos if no space is found:
1
2
3
4
5
6
size_t pos = name[i].find_first_of(' ');  // find the first space
if (pos != string::npos) {
    cout << "first space in " << name[i] << "is at position " << pos << '\n'
else {
    cout << " no space found in " << name[i] << '\n';
}

Topic archived. No new replies allowed.