Using std::getline() to read a single line? - c++

My goal is to prompt user to enter a message / sentence and then print it out on the screen, using getline(). The following is two different attempts I have tried out.
First Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
chat message[80];
cout << "\n what is your message today?" << endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
}
Second Attempt:
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main(){
string a = "a string";
cout << "\n what is your message today?" << endl;
while(getline(cin,a))
cout << a;
cout<<endl
}
}
For the fist attempt, the code simply print out "what is your message today?" and quit. I do not have a chance to enter any string at all. For the second attempt, it keeps asking me enter the message. Each time, when I enter something with the "\n", it would display what I entered on the screen. I use control + c to interrupt the running process to make it stop.
EDIT: To clarify and explain on my side, I extract the first attempt from a longer code, which is as the following.
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
char header[] = "\n *** C Strings ***\n\n"; // define a c string
int main()
{
char hello[30] = "Hello ", name[20], message[80]; // define a c string hello, declare two other c strings name and message
string a="fivelength";
cout << header << "Your first name: ";
cin >> setw(20) >> name; // Enter a word.
strcat( hello, name); // Append the name.
cout << hello << endl;
cin.sync(); // No previous input.
cout << "\nWhat is the message for today?"
<< endl;
cin.getline( message, 80); // Enter a line with a max of 79 characters.
if( strlen( message) > 0) // If string length is longer than 0.
{
for( int i=0; message[i] != '\0'; ++i)
cout << message[i] << ' ';
cout << endl;
}
return 0;
}
For the above code, it does not give me a chance to enter a message on the screen. I will put it as another question.

You are overcomplicating this, you can simply use std::string, which is the de-facto C++ string, and call the method, without using a loop.
You don't need a loop, since you are not going to repeatedly read lines, but only want to read one line, so no loop is needed.
#include <iostream>
#include <string> // not cstring, which is the C string library
using namespace std;
int main(void)
{
string message; // it can be an empty string, no need to initialize it
cout << "What is your message today?" << endl;
getline(cin, message);
cout << message;
cout<<endl;
return 0;
}
Output (Input: "Hello Stack Overflow!"):
What is your message today?
Message: Hello Stack Overflow!
PS: As #fredLarson commented, if you change chat to char in your first example, it should work. However, that code has a lot of commonalities with C.

Related

Can't I enter hangeul with std::cin?

I'm working at a super-simple program that if we enters a name, and it prints the entered name. It's easy but the problem is I live in korea and it's the hangeul(korean alphabet) so it must support hangeul
I tried this code:
#include <iostream>
#include <string>
using namespace std;
int main () {
string name = "";
cout << "이름을 입력하세요: "; getline(cin, name);
cout << "당신의 이름은 " << name << "입니다.";
return 0;
}
If we make it to english it will be:
#include <iostream>
#include <string>
using namespace std;
int main () {
string name = "";
cout << "Enter your name: ";
getline(cin, name);
cout << "Your name is " << name << ".";
return 0;
}
Looks easy. but if we put the hangeul in that cin,
Print:
Enter your name: 이름
Your name is .
and it just end. Of course the answer I wanted is:
Print:
Enter your name: 이름
Your name is 이름.
I've tried everything like using wide-character, change system locale and other many thing.
Here's the code I've tried:
#include <iostream>
#include <string>
using namespace std;
int main () {
setlocale(LC_ALL, "Korean");
string name = "";
cout << "이름을 입력하세요: ";
getline(cin, name);
cout << "당신의 이름은 " << name << "입니다.";
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main () {
wstring name = "";
cout << "이름을 입력하세요: ";
getline(wcin, name);
wcout << "당신의 이름은 " << name << "입니다.";
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main () {
wstring name = "";
cout << "이름을 입력하세요: ";
getline(wcin, name);
cout << "당신의 이름은 ";
wcout << name;
cout << "입니다.";
return 0;
}
If you can, please help me!
Try to check return value of the setlocale function, if it returns null, than it simply fails, if so try to search for another names for Korean system locale.
If you don't get an error in first paragraph, then check your comand prompt locale: press Windows+R, type 'cmd' and press Enter. In opened command prompt window type 'chcp' and press Enter. You should see output as shown below:
C:\Users\User>chcp
Active code page: 1251
1251 - this is mine coding page, means 'windows cp-1251'. After that google your coding page (you can find tables where each symbol placed with it's decimal representation on internet).
Compare some Korean symbol from your program with it's representation from coding table, you can output first symbol's decimal value like this:
int main () {
string name = "";
cout << "이름을 입력하세요: " << endl;
getline(cin, name);
cout << (int)name[0] << endl;
return 0;
}
If the number you get from program differs from coresponding number from your codding page, then you definitely need to search for another locale to set in your program, or to change the locale in your terminal.

Why are my if statements not working with strings in c++?

I'm a newbie with c++, and I tried googling a solution but every one I came across was so different from the issue I was facing so I couldn't figure it out. The problem I'm having is my "if" statements are completely ignored when I run the .exe from powershell.
https://pastebin.com/aE6MiQig
#include <iostream>
#include <string>
using namespace std;
int main()
{
string q;
string w;
string Bob;
string Emily;
{
cout << "Who is this? ";
cin >> q;
if (q == Bob)
{
cout << "Hey there bro. ";
}
if (q == Emily)
{
cout << "Hi friend :) ";
}
else
{
cout << "Oh hey " << q << ", how are you? ";
}
cin >> w;
cout << "Hey, that's " << w;
}
return 0;
}
When I input my name as "Bob" I should be seeing the message from the if statement "Hey there bro." but I am instead seeing the else statement, "Oh hey Bob, how are you?". Same goes when I input Emily. Only seeing the else statement.
I'm not getting any errors (running this in visual studio) so where am I messing this up?
Why not just compare directly to strings?
#include <iostream>
#include <string>
int main()
{
std::string q;
std::string w;
std::cout << "Who is this? ";
std::cin >> q;
if (q == "Bob") // note the quotation marks around Bob
{
std::cout << "Hey there bro. " << std::endl;
}
else if (q == "Emily") // note the quotation marks around Emily
{
std::cout << "Hi friend :) " << std::endl;
}
else
{
std::cout << "Oh hey " << q << ", how are you? ";
std::cin >> w;
std::cout << "Hey, that's " << w << std::endl;
}
return 0;
}
Also, you should avoid using namespace std because it leads to namespace pollution. Instead, you can just put std:: in front of string, cin, cout, and endl as I've done above, or include a using statement for each of those specifically, like this:
using std::string;
using std::cin;
using std::cout;
using std::endl;
std::string comes with its own operator==, comparing the string's contents.
string Bob;
string Emily;
Well, now you have created two strings, both using the default constructor, and so both are empty strings (i. e. they both would compare equal to "").
You need to assign them a value:
string Bob("Emily");
string Emily("Bob");
I deliberately assigned them inverse! Try this piece of code and you'll discover yourself that it is the content that is relevant for comparison, not the variable's name...
You obtain the value for string q from the user and compare it to string Emily or string Bob , neither of which have any values assigned.
The problem I'm having is my "if" statements are completely ignored when I run the .exe from powershell.
Your if statements are not being ignored instead you're comparing string q to "".
You can give string Bob and string Emily initial values:
#include <iostream>
#include <string>
int main()
{
std::string Bob = "Bob";
std::string Emily = "Emily";
std::string q;
}
This way you have something to compare the values you're getting from cin to:
#include <iostream>
#include <string>
int main()
{
std::string Bob = "Bob";
std::string Emily = "Emily";
std::string q;
std::cout<<"What is your name? ";
std::cin>>q; //Obtain value from cin
if(q == Emily){}//If q is Emily, then do something
}
You can read more about default variable values here and here.

Issue printing .txt file in program C++

I have a program that takes a text file and list the words and how many times they are used. It works but I can't figure out how to print out the text file. Above the sorted words and how many times they appear, I want to display the text from the file. How would I do that? I tried several things but it either does nothing or screws up the rest of the code saying there are 0 unique words. And lastly how would print out the results so they are more ... table -ish...
/*
Something like this:
Word: [equal spaces] Count:
ask [equal spaces] 5
anger [equal spaces] 3
*/
Thank you for any assistance you can provide me.
#include <iterator>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cctype>
using namespace std;
string getNextToken(istream &in) {
char c;
string ans="";
c=in.get();
while(!isalpha(c) && !in.eof())//cleaning non letter charachters
{
c=in.get();
}
while(isalpha(c))
{
ans.push_back(tolower(c));
c=in.get();
}
return ans;
}
string ask(string msg) {
string ans;
cout << msg;
getline(cin, ans);
return ans;
}
int main() {
map<string,int> words;
ifstream fin( ask("Enter file name: ").c_str() ); //open an input stream
if( fin.fail() ) {
cerr << "An error occurred trying to open a stream to the file!\n";
return 1;
}
string s;
string empty ="";
while((s=getNextToken(fin))!=empty )
++words[s];
while(fin.good())
cout << (char)fin.get(); // I am not sure where to put this. Or if it is correct
cout << "" << endl;
cout << "There are " << words.size() << " unique words in the above text." << endl;
cout << "----------------------------------------------------------------" << endl;
cout << " " << endl;
for(map<string,int>::iterator iter = words.begin(); iter!=words.end(); ++iter)
cout<<iter->first<<' '<<iter->second<<endl;
return 0;
}
I would just use a simple for loop like this:
for (int x = 0; x < words.size(); x++){
cout >> words[x] << endl
}
And then modify from there to get your desired format.
I did notice though, that you are not returning a value for main in all paths of the above code, which should give a compile time error, but did not when I compiled it, for some reason. I would remind you that you need to have a return value for main. Unless I am misunderstanding your question. I could not run this program without creating a sample file, and so could not test it without extra work. But the program did compile. I did not expect to, because of the missing return statement. If you can make this reproduce your error without me having to create a sample file of words, ei insert the list of words into the code and minimally reproduce the error, I would be able to help you better. As it is, I hope that I helped you.
Something like this should make it:
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
int main( int argc, char* argv[] )
{
std::string file;
std::cout << "Enter file name: ";
std::cin >> file;
std::fstream in( file.c_str() );
if ( in.good() )
{
std::unordered_map<std::string, int> words;
std::string word;
//Use this to separate your words it could be '\n' or anything else
char cSeparator = ' ';
while ( in >> word )
{
//Print the word
std::cout << word << cSeparator;
++words[word];
}
std::cout << std::endl;
//Headers Word and Count separated by 2 tabs
std::cout << "Word:\t\tCount:" << std::endl;
for ( auto& w : words )
std::cout << w.first << "\t\t" << w.second << std::endl;
}
in.close();
return EXIT_SUCCESS;
}
However this is assuming that the text file only contains the words, if you have other kind of stuff there, you should be able to filter it as you want.

Finding String on C++

I got a task from my teacher. I try some code but it confuses me a lot. So here's my code :
#include <iostream>
using namespace std;
char inputChecker [1000];
string source = "10110111000111001101110";
string detected;
int main(){
cout <<"Input:";
cin >> inputChecker;
for (int i=0;i<source.size();i++){
if (source[i]==inputChecker[0]){
cout <<"Data " <<inputChecker <<"is exist" <<endl;
}
else if (source[i]==inputChecker[i]){
cout <<"Data " <<inputChecker <<" isn't exist'" <<endl;
}
}
}
So ,my expectation output is ,when i input 10,it will result "Data 10 is exist". Without looping. I think it needed 2 kind of looping but i dont know where to loop.
My expectation output :
Input : 10
Data 10 is exist
Input : 25
Data 25 isn't exist
Thanks in advance :))
No need for loop
#include <iostream>
using namespace std;
int main() {
string source = "10110111000111001101110";
string input;
cin >> input;
if (source.find(input) != string::npos)
cout << input << " exists\n";
else
cout << input <<" doesn't exist\n";
}
Have a look at other useful std::string methods like find_first_of, find_last_of, etc.

Fix spacing in copycat program

Here is my code for a basic copycat program that just copys whatever the user types:
#include <iostream>
using namespace std;
#include <string>
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin;
}
return 0;
}
But when the user inputs more than one word i get this:
Me: more
You: than
You: Me: one
You: Me: word
You:
any and all help is appreciated! thank you!
You need to use cin.getline(usrin) instead of cin >> usrin.
cin >> usrin stops reading when it finds whitespace characters in the stream but leaves the rest of the stream for the next time cin is used.
cin.getline will read until the end of the line. However, you will need to change usrin to an array of char.
char usrln[MAX_LINE_LENGTH];
where MAX_LINE_LENGTH is a constant that is bigger than the length of the longest line you expect to see.
After each input, \n leaved behind in input buffer and read on next iteration. You need to flush your input buffer. Use
cin.ignore(MAX_INT, '\n'); //Ignores to the end of line
Add <limits.h> header.
#include <iostream>
#include <limits.h>
#include <string>
using namespace std;
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin ;//<<endl;
cin.ignore(INT_MAX, '\n');
}
return 0;
}