This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 4 years ago.
int main(){
char str1[MAX], str2[MAX];
cout <<" 1st string: ";
cin.get(str1, MAX);
cout <<" 2nd string";
cin.get(str2, MAX);
cout << str1 << str2;
return 0;
}
I am trying to input a string with spaces included in both arrays str1 and str2. The problem is program terminates after taking the first input.
On the output screen:
1st string : abc def
Now when I press enter to take input for 2nd array but then the code terminates and first string is displayed.
Output:
2nd string
abc def
How can I properly use this cin.get() function to take 2 different inputs? Is there any other way to take string with blank spaces for char array ?
std::string _str;
std::getline (std::cin, _str);
// std::getline (std::cin, _str, _char);
// if you wish to accept input until first appearance of _char
function getline() handles input that contains
embedded blanks or multiple lines.
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, address;
getline(cin, full_name); //reads embedded blanks
cout << “Your full name is: “ << full_name << endl;
getline(cin, address, ‘$’); //reads multiple lines
cout << “Your address is: “ << address << endl;
return 0;
}
first argument is the stream object from which the input will
come.
second argument is the string object where the text will be placed.
The third argument specifies the character to be used to terminate the input.
If no third argument is suppliedto getline(), the delimiter is assumed to be ‘\n’, which represents the Enter key.
Instead of cin.get() method use the following approach:
string s1,s2;
int max1,max2;
for (int i=0; i<max1; i++)
{
char ch = getchar();
while (ch != '\n' && ch != EOF) {
s1+=ch;
ch=getchar();
}
for (int i=0; i<max2; i++)
{
char ch = getchar();
while (ch != '\n' && ch != EOF) {
s2+=ch;
ch=getchar();
}
Related
I've tried this but I'm stuck honestly.
I'm trying to find the first character, and then search for the ending of that substring (for eg. if the word is "sandwich" and it finds 's' that it figures out that its "sandwich") and then write out the word sandwich. And also I'm new to C++.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s, word;
char a;
cout << "Enter the sentence that you desire: ";
getline(cin, s);
cout << "Enter the letter that you want: ";
cin >> a;
for (int i = 0; i < s.length; i++)
{
if (s[i] == a)
{
if (s[i] == '\0')
{
word = s;
cout << word;
}
}
}
return 0;
}
The request is a bit foggy but given also the code you posted, i think i got a heck of what you intend to do.
The easiest (yet not necessarily the most performing one) is to use a stringstream, more precisely an istringstream.
You basically build it with a string (the one you passed from keyboard) and then you use it as if it was your cin (it acts as a normalized istream).
At that point you can iterate each word of the sentence and check the first letter.
The first character of a string is either myString[0] or myString.front(). That is up to you.
the code should look like this :
#include <iostream> //cin/cout
#include <sstream> //istringstream
using namespace std ;
int main()
{
//first of all let's get our sentence AND the character you want
cout << "insert sentence here: " ;
string sentence ;
getline(cin, sentence) ;
cout << "insert the character here: " ;
char letter ;
cin >> letter ;
//then let's create an istringstream with said sentence
istringstream sentenceStream(sentence) ;
//let's then iterate over each word
string word ;
while(sentenceStream >> word)
{
//and see if the word starts with the letter we passed by keyboard
if(word.front() == letter)
{
cout << "the word \"" << word << "\" starts with '" << letter << "'\n" ;
}
}
return 0 ;
}
Just a couple of hints:
iostream includes string already, there is no need to re-include it.
[Edit] (as pointed out by whozcraig, this does not follow the standard. guards will "negate" the double inclusion anyway, so yes, including string is not a mistake. as specified in the comment, i'm yet to find an implementation of iostream that does not include string)[/Edit]
It is good practice not to call a variable 's', or 'a': use a name
that makes it recognizable.
You can find the end of a word with std::find_if:
#include <algorithm>
#include <string>
template <typename Is>
std::string find_word(Is& stream, char needle) {
auto const nonword = [](char c) {
if ('a' <= c && c <= 'z') return false;
if ('A' <= c && c <= 'Z') return false;
if (c == '-') return false;
return true;
};
for (std::string w; stream >> w;) {
if (w.size() && w[0] == needle) {
auto const last = std::find_if(std::begin(w),std::end(w),nonword);
return std::string(std::begin(w),last);
}
}
return "";
}
This takes any stream as argument, including std::cin, and can be invoked like this:
std::cout << find_word(std::cin,'w') << "\n";
It is important to specifically find the last character in each chunk handed you by the stream because the streams will only cut along whitespace by default. So if you enter a sentence:
Hello world!
You want the end of the word to be 'd', not '!'.
This question already has answers here:
getline not asking for input? [duplicate]
(3 answers)
Closed 2 years ago.
int main() {
string s1,s2;
cout<<"1. "<<endl;
cin>>s1; //to accept 1st string
cout<<s1<<endl;
cout<<"2. "<<endl;
getline(cin,s2); //to accept 2nd string
cout<<s2<<endl;
}
Here in the above code after accepting the 1st string it is not asking for the 2nd string: the program is getting terminated after taking the 1st input without waiting for the 2nd.
Could anyone kindly explain what the reason of such behavior is? And why is it not waiting for getline(cin,s2) for taking user input?
That is happening because getline reads \n at the end of your first line. So it read and printed "\n" while you think it expects a new line.
I suggest use getline twice (so firstly it reads \n, then your second line). And please, use std::, don't use using namespace std, and use spaces as any normal codestyling sais.
int main() {
std::string s1, s2;
std::cout << "1. " << std::endl;
std::cin >> s1; //to accept 1st string
std::cout << s1 << std::endl;
std::cout << "2. " << std::endl;
std::getline(std::cin, s2); //to accept \n
std::getline(std::cin, s2); //to accept 2nd string
std::cout << s2 << std::endl;
}
Here the error is there you need misunderstand the return type . Here you have used int for main method . So there you need return type. If you have used void for main method you haven't need a return type . You can use modify the code as below .
This is for printing single string
#include <iostream>
using namespace std;
int main(){
string s1;
cout<<" Enter the first string :"
getline(cin,s1);
cout<<"The input string is"<<s1 <<endl;
return 0;
}
You can modify the code as below to output the two strings as below
#include <iostream>
using namespace std;
int main(){
string s1,s2;
cout<<" Enter the First string :"
getline(cin,s1);
cout<<"The First string is"<<s1 <<endl;
cout<<" Enter the Second string :"
getline(cin,s2);
cout<<"The Second string is"<<s2 <<endl;
return 0;
}
I was attempting to print the first letter of each words in a sentence in C++. My idea was to print the first letter of a string first , then print every letter after a space:
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
string sentence;
int main(int argc, char const *argv[])
{
cout << "Input your name!" << endl;
cin >> sentence;
//output first character
cout << sentence[0] << endl;
//output the rest of first characters in words
for(int i = 0; i < sentence.length(); i++){
if (sentence[i] == ' ' && sentence[i+1]!= '\0'){
cout << sentence[i+1]<< endl;
}
}
return 0;
}
This solution only printed the very first letter of the string , and I was having trouble determining what went wrong with my code.
std::cin will stop reading into a string after the first whitespace. So, if you input hello world, it will only read "hello" into your string. Instead, you can read an entire line into your string using std::getline:
cout << "Input your name!" << endl;
getline(cin, sentence);
...
Also, the contents of a std::string won't have a nul character ('\0') in it whichever method you use, so your sentence[i+1] != '\0' check won't ever stop you from printing something.
I need to count the number of an input character there is in an input sentence. I am so close however I keep getting this error:
countchar.cpp:19:19: error: empty character constant
countchar.cpp: In function â:
countchar.cpp:26:75: error: could not convert â from â to â
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
void WordOccurenceCount(string, int);
int main()
{
char character;
string sentence;
char answer;
string cCount;
while(1) {
cout << "Enter a char to find out how many times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
cin >> sentence;
if(character == '' || sentence == "" )
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = WordOccurenceCount(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << cCount << character
<< "character(s)";
}
cout << "Do you wish to enter another sentence (y/n)?: ";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
int WordOccurrenceCount( string const & str, string const & word )
{
int count;
string::size_type word_pos( 0 );
while ( word_pos!=string::npos )
{
word_pos = str.find(word, word_pos );
if ( word_pos != string::npos )
{
++count;
// start next search after this word
word_pos += word.length();
}
}
return count;
Can anyone lend a hand?
There's no such thing as an empty character.
Just write
if (sentence == "")
{
cout << "Please enter a valid answer:\n";
break;
}
Problems with this code:
1. C++ does not take empty chars : if(character == '')
2. The arguments from your function WordOccurrenceCount do not match your declaration.
3. sentence.begin() is of String_iterator type, cannot be converted to string. (As expected by your WordOccurrenceCount function)
4. Again, sentence.end is also of String_iterator type, cannot be converted to int (As expected by your function declaration) or string (as expected by your function definition).
After counting (please mark erroneous lines somehow in the future) one of the problems was this line:
if(character == '' || sentence == "" )
In C++ (and C) you can't have empty character literals.
When you read the character and nothing is entered you get the newline, so the first check should be character == '\n'.
As for the string, there is a very simple method of checking if a string is empty: std::string::empty:
sentence.empty()
So the complete condition should be
if (character == '\n' || sentence.empty()) { ... }
As for the other errors, there are really multiple errors: To start with you declare WordOccurenceCount to take two arguments, a string and an integer. You then call it with three arguments, none of which are of the correct type.
Then in the definition of WordOccurenceCount you have different arguments compared to the declaration.
Finally, if you want to count the number of time a certain character is in a string, then you might want to look at the standard algorithms available in C++, especially std::count:
std::string sentence;
std::cout << "Enter a sentence: ";
std::getline(std::cin, sentence);
char character;
std::cout << "Enter a character to be found: ";
std::cin >> character;
long count = std::count(std::begin(sentence), std::end(sentence), character);
I was just trying something out and made the following code. It is supposed to take each individual letter in a string and print its ASCII equivalent. However, when there is a space, it stops converting. Here is the code:
#include <iostream>
#include <string>
using namespace std;
void convertToASCII(string letter)
{
for (int i = 0; i < letter.length(); i++)
{
char x = letter.at(i);
cout << int(x) << endl;
}
}
int main()
{
string plainText;
cout << "Enter text to convert to ASCII: ";
cin >> plainText;
convertToASCII(plainText);
return 0;
}
Any ideas on why this happens?
cin >> plainText reads from the input up to, but excluding, the first whitespace character. You probably want std::getline(cin, plainText) instead.
References:
std::getline
istream& operator>> (istream& is, string& str)
The formatted input function operator>> on istream stops extraction from the stream if it hits a space. So your string doesn't contain the rest of the input.
If you wish to read until the end of the line, use getline instead:
string plainText;
cout << "Enter text to convert to ASCII: ";
getline(cin, plainText);
convertToASCII(plainText);
Just Use getline and then no need such things you can just typecast to int a string letter to directly convert it to ascii.Here Is My Code.
#include <iostream>
#include <string>
using namespace std;
void convertToASCII(string s)
{
for (int i = 0; i < s.length(); i++)
{
cout << (int)s[i]<< endl;
}
}
int main()
{
string plainText;
cout << "Enter text to convert to ASCII: ";
getline(cin,plainText);
convertToASCII(plainText);
return 0;
}
Here is something I put together. I used a vector to store all of the ASCII values that are to be generated. We first ask the user for a string. Then we use type casting and add the values to a vector. We also use a while loop to prevent the user from not entering nothing.
# include <iostream>
# include <string>
# include <vector>
std::vector<int> converttoASCII (std::string s) //used a vector to store all our ASCII values
{
std::vector <int> vals; //vectpr creation
int ascChar;
for (int i = 0; i < s.length(); i++) //We interate through string passed and add to vectors
{
ascChar = s[i];
vals.push_back(ascChar);
}
return vals;
}
int main()
{
std::string toencode;
std::cout << "Please enter in a string to encode: ";
std::getline(std::cin, toencode);
while (toencode.length() == 0) //we used a for loop to prevent user from entering nothing.
{
std::cin.clear();
std::cout << "Must not be empty! Try Again.\n";
std::cout << "Please enter in a string to encode: ";
std::getline(std::cin, toencode);
}
std::vector <int> asciivals = converttoASCII(toencode);
for (int i : asciivals) //Print out the results of the vector
{
std::cout << i << "\n";
}
return 0;
}
References:
enter link description here
enter link description here
enter link description here
Simple and easy code
string mystring= "ABC DEF ++ -- ";
for (char c : mystring) cout << (int)c << endl;
This code will check characters one by one and output equivalent ascii value
Output: 65
66
67
32
68
69
70
32
43
43
32
45
45
32
cin.ignore();
cin.getline(plaintext,100); // 100 (assumed) is the size of plaintext
Use these two lines of code to accept a string with blank spaces.