I want it so that i can enter multiple things upon input. Here's my code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char dot;
    dot = '.';
    
    string sztext1;
    string sztext2;

          cin >> sztext1 >> dot >> sztext2;
          cout << "Works..." << endl;
          system("pause >nul");
          return 0;
}

Example, if I enter much.love, it doesn't output "Works..."

Recommended Answers

That is because cin is looking for a whitespace between each input(' ' or '\n'). So if you typed "much . love" it would work the way you have it set up now, but if you typed "much.love" then sztext1 would be "much.love" and it doesn't show Works... because it …

Jump to Post

All 4 Replies

That is because cin is looking for a whitespace between each input(' ' or '\n'). So if you typed "much . love" it would work the way you have it set up now, but if you typed "much.love" then sztext1 would be "much.love" and it doesn't show Works... because it is waiting for input of dot and sztext2.

Thanks for that! What would I need to do in order to allow me to enter without spaces for it to work?

You would need to read the input in as a string then parse the string and store each part into variables.

If '.' was always your word separator then you could use the find and substring functions that are part of the string class.

Here is an example of this.

#include <iostream>
using namespace std;

int main()
{
	char dot = '.';
	string str = "", word1 = "", word2 = "";
	getline(cin, str); //takes in the whole line (this reads in all spaces up to a newline character '\n'

	word1 = str.substr(0, str.find(dot)); //creates a substring from the start of the string up to the dot
	word2 = str.substr(str.find(dot)+1, str.length()); //creates a substring from the dot to the end of the string

	//outputs each word
	cout << word1 << endl;
	cout << word2 << endl;

	return 0;
}

Thank you, you are the perfect help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.