Exit loop unless input not given - c++

int main()
{
string name;
while(cin>>name)
{
if(name=='\n')
break;
else
{
cout<<name;
}
}
cout<<"Exited";
}
Here I need to get input till the user didn't give input or skips with the new line. I am unable to complete the code.

Thisngs to watch:
Lets add the correct headers.
Lets not do the using namespace std; as it causes problems.
Let use getline() rather than operator>> so we can see a whole line
Lets use std::string rather than a C-array of char.
Can check for empty line as part of the while test.
Lets add '\n' so we can see the output.
Lets do some nice formatting.
Result:
#include <iostream>
#include <string>
int main()
{
std::string name;
while(std::getline(std::cin, name) && name != "")
{
std::cout << name << "\n";
}
std::cout << "Exited\n";
}

The new line character '\n' is a white space character that by default is skipped by the operator >> for the input stream. Instead use for example member function getline.
Here is a demonstrative program
#include <iostream>
int main()
{
char name[30];
while ( std::cin.getline( name, sizeof( name ) ) && name[0] )
{
std::cout << name << std::endl;
}
std::cout << "Exited\n";
return 0;
}

You have several problems in your code
First of all you cant put " cin >> name " in while condition
it's completely wrong .
you have arrays of characters ( name [30])
and then you want to compare it with user's input , in you didn't declare the array so its wrong
then again in your next condition name == '\n' is not valid for what you want
in our cmd console we can only put a characters you can't use '\n'
in the end of main function you have to return something (maybe its confusing )
just write "return 0;" in the end and it will be OK
i recommend you using this code::
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
char name[30];
while(1)
{
cin >> name;
if( name[0] =='E')
break;
else
{
cout<<name;
}
}
cout<<"Exited";
return 0;
}
if user enter 'E' character , if conditions becomes true and we exit while.

Use std::string.
#include <iostream>
#include <string>
int main()
{
while (true)
{
std::string name;
std::cout << "Enter a name: ";
getline( std::cin, name );
if (!std::cin or name.empty())
break;
// do stuff with name here
}
std::cout << "Exited\n";
}

Related

Loop returning Message depending on how many characters you type

How come the loop is returning the message Enter # when done MORE instead of once depending on how many words you enter? EG type a single letter it loops the message Enter # when done but if you type what? it returns it Enter # when done x4 ....the same amount of letter in the word.I am new to c++ coming from c so im confused.Dont worry about other stuff in the code I need help with this. Thank you :)
#include <iostream>
#include <stdio.h>
int main() {
char sup;
while (sup != '#') {
std::cout << "Hi\n";
std::cout << "Enter # when done";
std::cin >> sup;
if(sup == '#') {
std::cout << "Ok you want to go.";
}
}
std::cin.get();
}
Example with std::string
// preferably do not include stdio.h in C++ programs
#include <string>
#include <iostream>
int main()
{
std::string input; // use standard library string class
while (input != "#")
{
std::cout << "Hi\n";
std::cout << "Enter # when done : ";
std::cin >> input;
if (input == "#")
{
std::cout << "Ok you want to go.\n";
}
}
return 0; // <== important to otherwise your program is ill-formed
}
As you set in while loop that (sup != '#'), it will take input character until you type #.

Convert char array to a string with cin.getline(.)

hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}

Keep getting "member reference base type 'string [1000]' is not a structure or union" error and dont know how to fix it?

This program reads an SSN from the user and checks if it matches an SSN in a text file provided. Tried switching the array to a vector and it didnt work. Tried putting the array in the structure function and using info:: but nothing seems to work. I know this is pretty basic but I cant get it, thanks.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
struct info{
string SSN;
string firstName;
string lastName;
};
string list[1000];
string userSSN;
char x;
fstream input(argv[1]);
int i = 0;
while(!input.eof()){
input >> list.x[i] >> list.SSN[i] >> list.firstName[i] >> list.lastName[i];
i++;
}
input.close();
cout << "Input a SSN:" << endl;
cin >> userSSN >> endl;
for(int k = 0; k < i; k++){
if(userSSN.compare(list.SSN[k]) == 0){
cout << "Found at location " << k << endl;
}
}
}
list is just an array of 1000 std::strings. It looks like you need it to be of type info. Even that won't solve your problems as info has no member named x. After that, to access a member of info in an array would be like
list[i].SSN
not
list.SSN[i]
There are so many things wrong with this code that I don't know where to start. Let's see:
Using using namespace std; is almost always a bad idea, and if you have an identifier list, then it's even worse because it conflicts with std::list.
Using std::string without #include <string> is not guaranteed to work. It may work if you include some other standard header, but don't rely on it.
Your variable x is unused.
string list[1000]; should probably be info list[1000];.
list.SSN[i] et al should probably be changed to list[i].SSN.
list.x[i] does not make sense at all and can probably be removed. (Or you meant to read into the otherwise unused x to skip parts of the file.)
You cannot read from std::cin into std::endl. Remove std::endl from that line.
Using std::string's compare function is pretty strange here, just use ==.
The issues in your code were already pointed out in other's answers. I'll show you a "working" example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::cin;
struct info {
char x; // You were reading that from the file so I added it
string SSN;
string firstName;
string lastName;
friend std::istream &operator>>( std::istream &is, info &i ) {
// maybe you should check data input somehow...
is >> i.x >> i.SSN >> i.firstName >> i.lastName;
return is;
}
};
int main(int argc, char* argv[]) {
// check if a file name has been passed as a parameter
string file_name;
if ( argc < 2 ) {
cout << "Please, enter the input file name:\n";
cin >> file_name;
}
else
file_name = argv[1];
std::ifstream input(file_name);
if ( !input ) {
std::cerr << "Error. Unable to open file: " << file_name << '\n';
exit(-1);
}
// Just use a vector to store all the structs
vector<info> my_list;
info temp_info;
while( input >> temp_info ) {
my_list.push_back(temp_info);
}
input.close();
cout << "Input a SSN: ";
string userSSN;
cin >> userSSN;
// That's not cheap. You may want to change the container or sort it
for ( int k = 0; k < my_list.size(); k++ ) {
if ( userSSN == my_list[k].SSN ) {
cout << "Found at location " << k << '\n';
}
}
return 0;
}

Writing to a file with fstream and cstring

#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char filename[20] = "filename";
char userInput;
ofstream myFile;
cout << "Enter filename: ";
cin.getline(filename, sizeof(filename));
myFile.open(filename);
if(myFile.fail())
{
cout << "Error opening file: "
<< filename << "\n";
return 1;
}
cout << "Add text to the file: ";
cin.get(userInput);
while(cin.good() && userInput)
{
myFile.put(userInput);
cin.get(userInput);
}
myFile.close();
return 0;
}
Im having trouble terminating the input without force quiting it(It still writes to the file).
This is what I am supposed to do
Receives a line of input from the user, then outputs that
line to the given file. This will continue until the line input
by the user is “-1” which indicates, the end of input.
however I cannot work out the -1 part. Any help would be greatly appreciated everything else seems to work.
You're making things a bit more complicated than they need to be. Why C strings instead of std::string, for example? Using the right (standard-provided) classes generally leads to shorter, simpler and easier-to-understand code. Try something like this for starters:
int main()
{
std::string filename;
std::cout << "Enter filename" << std::endl;
std::cin >> filename;
std::ofstream file{filename};
std::string line;
while (std::cin >> line) {
if (line == "-1") {
break;
}
file << line;
}
}
First of all, the assignment asks to read a line from the user, character-wise input by get() shouldn't be the function to use. Use the member function getline() as you did to recieve the file name and use a comparison function to check against -1:
for (char line[20]; std::cin.getline(line, sizeof line) && std::cin.gcount(); )
{
if (strncmp(line, "-1", std::cin.gcount()) == 0)
break;
myFile.write(line, std::cin.gcount());
}

Password function and arrays

I'm writing a simple password program, but the else if statement always applies, even if the password is put in correctly. This works fine if I use a single char instead of an array, and change "hotdog" to 'h', and I think it might have something to do with unseen characters, like a space or return. I was sure cin.ignore() took care of return/enter.
Sorry, I'm fairly new to programming.
#include <iostream>
int main()
{
std::cout << "What is the password?\n" << std::endl;
char password[20] = "NULL";
std::cin >> password;
std::cin.ignore();
std::cout << password << " is your entry?\n";
if (password == "hotdog")
{
std::cout << "Correct!";
}
else if (password != "hotdog")
{
std::cout << "Incorrect!";
}
else
{
}
std::cin.get();
}
Firstly, change char password[20] to string password. This prevents a buffer overflow if they type in more than 20, and it enables you to use == for string comparison.
The code std::cin.ignore() ignores a single character. You want to actually ignore the entire remainder of the line. There is no way to ignore "everything else typed so far" because there may have been characters typed which are still buffered. In practice, it works well to treat input as a series of lines.
The most accurate way to ignore the rest of the line is to ignore all characters up to and including '\n', which appears in the input stream at the end of the line (by definition).
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
which may require #include <limits>. Another way is to read a string and discard it:
std::string t;
std::getline( std::cin, t );
NB. Check your understand of if...else . Once you have if ( condition ), then the next else will already get everything that was not in that condition. It's pointless to actually write else if ( !condition ); and your final else { block can never be entered, because the previous two conditions were exhaustive.
The problem is with how you are using the if-else statement. Try this code out:
#include <iostream>
int main()
{
std::cout << "What is the password?\n" << std::endl;
char password[20] = "NULL";
std::cin >> password;
std::cin.ignore();
std::cout << password << " is your entry?\n";
if (stricmp("hotdog", password) == 0)
{
std::cout << "Correct!";
}
else
{
std::cout << "Incorrect!";
}
std::cin.get();
}
When I take your code and compile it, even the term hotdog does not work properly, I obtain the following:
What is the password?
hotdog
hotdog is your entry?
Incorrect!
As suggested above, a string is a better method and works as intended based on your requirements. Here is sample replacement code that works as intended (with this code spaces are allowed, with the other answers, spaces are not, it all depends what is intended):
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char ** argv)
{
cout << "What is the password?\n" << endl;
string password = "NULL";
getline(cin, password);
cout << password.c_str() << " is your entry?\n";
if (password == "hotdog")
{
cout << "Correct!";
}
else if (password != "hotdog")
{
cout << "Incorrect!";
}
else
{
// Added from original; however, this should never occur
cout << "Else?";
}
system("pause");
return 0;
}
Output of Replacement Code
What is the password?
hotdog
hotdog is your entry?
Correct!
You had to use strcmp() function to compare strings properly in c++,so I added the cstring library:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main(){
string password;
cin >> password;
cout << password << " is your entry?\n";
char hd [7] = "hotdog";
if (strcmp(password.c_str(),hd) == 0){
cout << "Correct!\n";
}
else if (strcmp(password.c_str(),hd) != 0){
cout << "Incorrect!\n";
}
else{
cin.get();
}
}