Can't I enter hangeul with std::cin? - c++

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.

Related

VS code c++ cin not working with string type

This is a simple hello program, but it shows nothing if I run it.
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Please enter your name: ";
string username;
cin >> username;
cout << "hello, " << username << ", ..., goodbye\n";
}
output:
nothing in the terminal
The single cout can work, so I guess that might be the problem with buffer caused by string.
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Please enter your name: ";
//string username;
//cin >> username;
//cout << "hello, " << username << ", ..., goodbye\n";
}
output:
Please enter your name:
But adding flush doesn't make it work.
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Please enter your name: ";
string username;
cin >> username;
cout << "hello, " << username << ", ..., goodbye\n" << flush;
}
output: nothing in the terminal
Then I change the type of username to char, int, and they all work properly.
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Please enter your name: ";
char username;
cin >> username;
cout << "hello, " << username << ", ..., goodbye\n";
cout << "Please enter your name: ";
int username;
cin >> username;
cout << "hello, " << username << ", ..., goodbye\n";
}
output:
Please enter your name: asdf
hello, a, ..., goodbye
Please enter your name: 123
hello, 123, ..., goodbye
The above are run by code-runner, so I try to compile manually, but it still doesn't work.
DINO#DINO-Amadeus MINGW64 /d/DINO/code/essential_c++
$ g++ -o chap1 chap1.cc
DINO#DINO-Amadeus MINGW64 /d/DINO/code/essential_c++
$ ./chap1
DINO#DINO-Amadeus MINGW64 /d/DINO/code/essential_c++
$
Can anyone help with this? Many thanks.
I am able to compile your first example,
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter name" << endl;
string username;
cin >> username;
cout << "Hello, " << username << ", goodbye\n";
}
and have it work in Codeblocks' console as expected.
Enter name
John Doe
Hello, John, goodbye
Process returned 0 (0x0) execution time : 3.623 s
Press any key to continue.
It also compiles manually through cygwin.
*****#DESKTOP-******* /cygdrive/c/Users/*****/Documents/Programs/Test/test
$ g++ main.cpp -o main
*****#DESKTOP-******* /cygdrive/c/Users/*****/Documents/Programs/Test/test
$ ./main
Enter name
John Doe
Hello, John, goodbye
All this makes me think the code is fine, and the real problem is elsewhere. You said you are using coderunner. Is this for a class? You might be able to see what other students are doing different.
EDIT 10/9/2021
Lets try the following to see what is messing up:
Whether the problem is with the namespace, see if the below code works: (If you type "Hello", it will print "Hello")
#include <iostream>
#include <string>
int main() {
std::string username;
std::cin >> username;
std::cout << username;
}
To see if the problem is with cin, try this (It should output "Hello")
#include <iostream>
#include <string>
int main() {
std::string username = "Hello";
std::cout << username;
}
And, as a moonshot: (Same behavior as (1))
#include <iostream>
int main() {
char* username[5];
scanf("%s",&username);
printf("%s",username);
}
Try changing the extension of VSCode which runs your code, and update to the latest version if you can. If you are using .run, try C/C++ Compile Run by danielpinto8zz6 or similar.

Is it possible to put multiple names in one string?

I just started learning C++ and I'm currently following a tutorial on YouTube.
I thought it was fun to make a very simple 'access' program. If I type in my name it says, "Welcome!" If I type in another name it says, "access denied". It worked perfectly fine, but then I wanted the program to say "Welcome!" to two different names. So, I wanted to add a second name in the string, but I couldn't figure out how to do that. I googled a lot but I couldn't find anything. In the end, I came to string name = ("Joe", "Sean");, but here, it was only valid for Sean. I just can't figure out how to put multiple names in one string and make them both work. I hope you can help me, here is my code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name = ("Joe", "Sean");
string input;
cout << "What is your name?\nMy name is: ";
cin >> input;
if(input == name){
cout << "Welcome, "<< input <<"! ";
} else {
cout << "Access denied";
}
return 0;
}
This is a way to do it using a vector of strings, so you can adapt easily with more names :
#include <iostream>
#include <vector>
using namespace std;
void printMessage(string message)
{
std::cout << message << std::endl;
}
int main()
{
vector<string> names{"Joe", "Sean", "Paul"};
string input;
cout << "What is your name? " << endl;
cin >> input;
for (string name : names)
{
if (name == input)
{
printMessage("Welcome!");
return 0;
}
}
printMessage("Access Denied!");
return 0;
}
The problem is in the string variable "name". You need an array of strings, not a single string.
This is an example implementation:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string names[] = {"Joe", "Sean"};
string input;
cout << "What is your name?\nMy name is: ";
cin >> input;
for (int i = 0; i < end(names) - begin(names); i++) {
if(input == names[i]){
cout << "Welcome, "<< input <<"! " << endl;
return 0;
}
}
cout << "Access denied" << endl;
return 0;
}
You encountered some quirky features of C++ in the approach you are using to initialize your string variable:
string s1 = ("Joe"); // creates a string "Joe"
string s2 = ("Joe", "Sean"); // creates 2 strings, "Joe" and "Sean", and the variable s2 stores only the latter!
For more details on the different methods for initializing variables there has been an interesting discussion in this previous question.

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

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.

Im using a vector and file reader,the goal is that it should print info from text file like name and lastname

I'm using a vector and file reader, the goal is to print info from a text file like name and last name using a search algorithm, like a phone book.
I have tried using find, and it works, because it finds specific input of what I write. But I want it to work like a phone book. If I searched a name, it should print out the last name and phone number.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector<string> person;
string word;
ifstream out;
out.open("a.txt");
while (!out.eof()) {
getline(out, word);
person.push_back(word);
}
string item;
std::cout << "Write the name you want to search" << item << "\n";
cin >> item;
if (find(person.begin(), person.end(), item) != person.end()) {
std::cout << "Namn::" << item << "\n";
}
else {
std::cout << "not found" << "\n";
}
// John from text file a.txt, but if possible it should print out his last name and
// mobile
// like this.
// John
// Stock
// 0700044
system("pause");
return 0;
}

C++ beginner, need guidance

I am a c++ beginner and I am curious to why this does not work:
#include <iostream>
using namespace std;
int main ()
{
int firstname;
int lastname;
cout << "My name is " << firstname << lastname;
cin >> firstname >> lastname;
cout << endl;
return 0;
}
I want the output to simply be where the user inputs their first name and the last name and it turns out to be as follows:
Example:
My name is John Doe.
#include <string>
...
string firstname;
string lastname;
int values hold numbers. To store names, use strings.
cin >> firstname >> lastname;
cout << "My name is " << firstname << " " << lastname;
Then make sure to read the names before you print them. The cin and cout should be swapped. I've also added a space (" ") in the printout between the two variables.
#include <iostream>
#include <string> // so you can use string
using namespace std;
int main() {
string first;
string last;
cin >> first;
cin >> last; // getting input from using and storing it in last
cout << "My name is " << first << last << endl; // printing out "My name is and " and what you wrote for first and last
return 0;
}
cout << "My name is ";
cin >> firstname >> lastname;
cout << firstname << " " << lastname;
This should output a single line of:
My name is John Doe
Plus, strings of characters are stored in string types, not int types
So you'd have to include <string>, and change the ints to string
Name can be of int type change it to std::string
Here is the modified code will produce output as you want.
#include <iostream>
int main ()
{
std::string firstname;
std::string lastname;
std::cin >> firstname >> lastname;
std::cout << "My name is " << firstname<<" " << lastname<<"\n";
return 0;
}
Note that the you will have to add " " while printing if you want a white space between your first name and last name.
Try to take input using 'getline(cin,str); if your string contain white space too.
I would suggest you to not to use standard namespace i.e. using namespace std; while writing the code. For more detail please have a look of link provided below
Why is "using namespace std" considered bad practice?
First I would try to prompt the user to enter their first and last name. Or else how would they know what to enter? And using int type does not help at all because the user would be entering a string and not an integer. Try this ...
#include <iostream>
using namespace std;
int main() {
cout << "Pleas enter your first and last name." << endl;
string name;
cin >> name;
cout << "Hello " << name << endl;
return 0;
}
Make sure that the user knows what to input (first and last name) otherwise they will not know what to input. This is the output code you can use:
cout << "Please enter your first and last name." << endl;
So the full code should look something like this:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string firstname;
string lastname;
cout << "Please enter your first and last name: " << endl;
cin >> firstname >> lastname;
cout << "My name is " << firstname << " " << lastname;
cout << endl;
return 0;
}
You are doing
int firstname;
int lastname;
meaning that you want to get an integer value, however you want a string. So, replace the int with std::string or string in your case. Also, remember to #include <string> to get the string functionality. After doing this, you should be able to input and return letters. :D
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string firstname;
string lastname;
cout << "My name is " << firstname << lastname;
cin >> firstname >> lastname;
cout << endl;
return 0;
}
Might I add that you generally should not use using namespace std; as it is considered bad practice, it also is not really necessary, you could just type std::.... using namespace std is used if you do not want to type the namespace name every time, but it's generally better to distinguish between which type of functions you want to use with the same names but in different namspaces. and using '\n' for a new line as well instead of endl. This is because endl takes more time to complete than \n.
I recommend to also include the namespace in your code if you are a beginner. In simple cases like printing strings its readable but a better practice if you're learning to include std::string, std::cin, and std::cout. In this case the :: just means to grab the keyword(right value) from its namespace(left value).