c++ program needs small addition

so im done with my program but i have small problem
this is my program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main ()
{
	string a;
	char j[100];
	int i, c, b; 
	cout <<"enter your name ";
		getline(cin,a);
		cout << " ur name is " << a << endl;
c=a.size(); 
for (b=0; b<=c; b++)
{
j[b]=a[b];
j[b]='\0';
}
system ("pause");
return 0; 
}

how can u print every word typed on a different line?
Don't use "" for standard header includes, use <> - e.g. #include <iostream>

Option 1, read each word and immediately print it:
1
2
3
4
5
std::string word;
while(std::cin >> word)
{
    std::cout << word << std::endl;
}
Option 2, if you already have the entire line, you can get it into a stream again and do option 1:
1
2
3
4
5
6
7
8
9
10
std::string line;
while(std::getline(std::cin, line)) //read entire line
{
    std::istringstream iss {line}; //need to #include <sstream>
    std::string word;
    while(iss >> word)
    {
        std::cout << word << std::endl;
    }
}
Last edited on
This is a duplicate post I think...anyway

Try to use this and if this works, try to understand or ask questions for you to learn and not just simply copy this.

This will handle multiple word first names by the way but can not handle middle or last name with multiple words.

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
34
35
36
37
38
39
40
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    string name;
    vector<string> tokens;

    cout << "Enter a full name (Format: First Middle Last): ";
    getline(cin, name);

    // break line into words and save to a vector array
    char *token = strtok((char *)name.c_str(), " ");
    while (token) {
        // save token to array
        string s(token);
        tokens.push_back(s);

        // get next token
        token = strtok(NULL, " ");
    }

    // Get first name and print
    cout << "First name: ";
    for (int i = 0; i < tokens.size() - 2; i++) {
       cout << tokens[i] << " ";
    }
    cout << endl;

    //Get middle name and print
    cout << "Middle name: " << tokens[tokens.size() - 2] << endl;

    //Get last name and print
    token = strtok(NULL, " ");
    cout << "Last name: " << tokens[tokens.size() - 1] << endl;

    return 0;
}
Topic archived. No new replies allowed.