Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 17 days ago.
Improve this question
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
using namespace std;
struct customer
{
char fname[11];
};
void name(customer& name)
{
bool check = false;
do {
cout << "Enter your first name : ";
cin.getline(name.fname, 10);// goal is to exit once press enter
if (name.fname == '\n') //This doesnt work. i also tried using cin.get, cin.ignore, cin.peek and it still doesnt work, i tried changing the '\n' to '\0' and 0 just to see.
{
cout << "Invalid Entry\n";
}
else
check = true;
} while (check != true);
}
int main()
{
customer cr;
name(cr);
return 0;
}
I created this code just to finally figure out how to use cin.getline(), its a simple code where it takes a name.
The goal is to enter a name and exit the code when pressing Enter.
you dont mean
if (name.fname == '\n')
you mean
if (name.fname[0] == '\n')
You are trying to compare a char[] array to a single char, which will not work. Use a string comparison like strcmp() instead. However, cin.getline() will not store the terminating '\n' into fname to begin with.
Try something more like this instead:
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
using namespace std;
struct customer
{
char fname[11];
};
void name(customer& name)
{
bool check = false;
do {
cout << "Enter your first name : ";
if (!cin.getline(name.fname, 11))
break;
//if (name.fname[0] == '\0')
if (strcmp(name.fname, "") == 0)
cout << "Invalid Entry\n";
else
check = true;
}
while (!check);
}
int main()
{
customer cr;
name(cr);
return 0;
}
That said, you really should be using std::string instead of char[], eg:
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <iostream>
using namespace std;
struct customer
{
string fname;
};
void name(customer& name)
{
bool check = false;
do {
cout << "Enter your first name : ";
if (!getline(cin, name.fname))
break;
if (name.fname == "")
cout << "Invalid Entry\n";
else
check = true;
}
while (!check);
}
int main()
{
customer cr;
name(cr);
return 0;
}
Try this code
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
struct customer
{
char fname[11];
};
void name(customer& name)
{
bool check = false;
do {
std::cout << "Enter your first name : ";
std::cin.getline(name.fname, 10);
if (std::cin.fail() || name.fname[0] == '\n')
{
std::cout << "Invalid Entry\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else
check = true;
} while (check != true);
}
int main()
{
customer cr;
name(cr);
return 0;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Write a program that “bleeps” out words that you don’t like; that is, you read in words using cin and print them
again on cout. If a word is among a few you have defined, you write out BLEEP instead of that word. Start with
one “disliked word” such as
string disliked = “Broccoli”;
When that works, add a few more.
So i was thinking on how i could create a code that would do that with a set of words using a vector, but all i could come up with was
int main()
{
vector<string> disliked = { "damn","stupid","fat" };
string word = "";
while (cin >> word) {
bool bad = false;
for (string x : disliked) {
if (x == word)
bad = true;
}
if (bad)
cout << "Bleep\n";
else
cout << word << "\n";
}
return 0;
}
i feel like that code can be shortened with taking out one of the if statements but i can't find a working way to do it.
overall it seems like more code than it should be for this simple check, also could the for part be done better? doing a whole loop of the whole vector seems to be too resource intensive in a case where the vector has lets say a 1000 words, maybe separating it by an if statement checking for a-d, f-j... etc, and then only running a for loop would be less heavy?
Sort your vector and use std::binary_search:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> disliked = { "damn","stupid","fat" };
sort(std::begin(disliked), std::end(disliked));
std::string word = "";
while (std::cin >> word)
{
if ( binary_search(std::begin(disliked), std::end(disliked), word))
{
std::cout << "Bleep ";
}
else
{
std::cout << word;
}
}
}
or use std::set instead of vector:
#include <iostream>
#include <set>
#include <algorithm>
int main()
{
std::set<std::string> disliked = { "damn","stupid","fat" };
std::string word = "";
while (std::cin >> word)
{
if ( disliked.find(word) != std::end(disliked) )
{
std::cout << "Bleep ";
}
else
{
std::cout << word;
}
}
}
Both of these solutions have logarithmic complexity for the word lookup instead of linear.
Use the std::find operation on a vector.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> disliked = { "damn","stupid","fat" };
string word = "";
while (cin >> word) {
if ( std::find(disliked.begin(), disliked.end(), word) != disliked.end() )
{
cout << "Bleep ";
}
else
{
cout << word;
}
}
return 0;
}
That's the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
string name = "lol";
int score = 0;
vector<string>names;
vector<int>scores;
bool choose = true;
for (int l = 0; name != "stop"; ++l) {
cin >> name >> score;
if (name == names[l]) choose = false;
if (choose == true) {
names.push_back(name);
scores.push_back(score);
}
else cout << "error, name already used" << endl;
choose = true;
}
}
When I run the program, and I type a name followed by a score, it says: "debug assertion failed: vector subscription out of range".
Why? And how do I eliminate this error?
You try get element that doesn't exist. First you need push something to
vector<string> names;
or do check if names is empty:
if (!names.empty())
if(name == names[l])
choose = false;
also looking what you want achieve, it's seems that you have anyway wrong code, you only look at the last name you have added. So to help you a bit this solution works better:
int main()
{
string name;
vector<string> names;
while (cin >> name && name != "stop")
{
bool choose = true;
for (auto i : names)
{
if (name == i)
choose = false;
}
if (choose)
{
names.push_back(name);
}
else cout << "error, name already used" << endl;
}
}
I'm writing a console application for managing and tracking characters, monsters, turn order and conditions applied to make my battle run faster in DnD. The following code works perfectly on Windows but when I tried to compile it on my laptop, which runs Linux, it no longer works.
I input a name, then the initiative, then max health, then when I go to add another character it just reads a blank string and sets that as the name. I'm at a loss...
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
void gValid_Input(std::string& var, std::string question = "Add the carriage return manually if you want it...") {
using namespace std;
do {
cin.clear();
cin.sync();
cout << question;
} while (!getline(cin, var));
}
template <typename t>
void gValid_Input(t& var, std::string question = "Add the carriage return manually if you want it...") {
using namespace std;
do {
cin.clear();
cin.sync();
cout << question;
} while (!(cin >> var));
}
void gValid_Option(char& response, std::vector<char> valid_Responses = {'y','n'}){
using namespace std;
const char diff = 'a' - 'A';
do{
cin.clear();
cin.sync();
cin >> response;
if (response >= 'A' && response <= 'Z'){
response += diff;
}
} while (find(valid_Responses.begin(), valid_Responses.end(), response) == valid_Responses.end());
}
void gValid_Option(char& response, std::string question, std::vector<char> valid_Responses = {'y','n'}){
using namespace std;
const char diff = 'a' - 'A';
do{
cin.clear();
cin.sync();
cout << question;
cin >> response;
if (response >= 'A' && response <= 'Z'){
response += diff;
}
} while (find(valid_Responses.begin(), valid_Responses.end(), response) == valid_Responses.end());
}
SOLVED
void gValid_Input(std::string& var, std::string question = "Add the carriage return manually if you want it...") {
using namespace std;
do {
cin.clear();
cin.sync();
cout << question;
if (cin.peak() == '\n'){
cin.ignore(1, '\n');
}
} while (!getline(cin, var));
}
I have problem with this question I don't know what is wrong with my code that I get Presentation Error every time I don't know what is the format of output can you help me to solve this question I am sorry that my code is a little confusing
here is the link of question http://sharecode.ir/section/problemset/problem/1208
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
int main()
{
string temp=" ";
bool cheak3=false,cheak4=false;
int n,num;
cin>>n;
while(n != 0)
{
if(cheak4 == true)
cout<<endl;
cheak4=true;
cin>>num;
cheak3=false;
string cheak1,cheak;
while(1)
{
if(num ==-1)
break;
getline(cin,temp);
for(int i=0 ; i<temp.size() ; i++)
{
if(temp[i] != ' ')
cheak.push_back(temp[i]);
else
{
reverse(cheak.begin(),cheak.end());
cheak1+=cheak;
cheak.clear();
if(cheak3 == true)
cheak1.push_back(' ');
}
}
reverse(cheak.begin(),cheak.end());
cheak1+=cheak;
cheak.clear();
num--;
if(cheak3 == true)
{
cheak1.push_back(' ');
cout<<cheak1<<endl;
cheak1.clear();
}
cheak3=true;
}
n--;
}
}
I believe the tricky part is you should print a blank line between the output blocks.
Your code has too complicated logic! Here is my solution to this problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
int N, lines;
string word;
cin>>N;
while (N--) {
cin>>lines;
while (lines--) {
char end;
do {
cin >> word;
end = cin.get();
for (int i=word.length()-1;i>=0;i--) cout<<word[i];
cout << end;
} while (end != '\n');
}
if (N) cout << endl;
}
return 0;
}
The line if (N) cout << endl; makes sure you print a newline character for every output block except the last one (when N equals to 0).
After reading each word in a line, you can use cin.get(); in order to determine the next character. If it is a space, then print it and read the next word. Else if it is a \n print it and go to next line! :)
I'm not sure where to go from here. I know something needs to go after ifstr.get(c). It copies the exact words that I have in my text file called project.txt but I just need to remove any words that have the chars < or >?
Any help would be great. Thanks:)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
char c;
ifstream ifstr("project.txt");
ofstream ofstr("past.txt");
if(ifstr.fail()){
cout<<"error!"<<endl;
} // if
ifstr.get(c);
while(!ifstr.eof()) {
cout<<c;
ifstr.get(c);
ofstr<<line<<endl;
} // while
cout<<endl<<"copy complete"<<endl;
ifstr.close();
ofstr.close();
system ("pause");
return 0;
} // main
Pseudo-code (iostream-esque conditions) for the question in title (also removes the angle brackets):
char c;
while (read_char_succeeded(&c))
if (c == '<')
while (read_char_succeeded(&c) && c != '>')
;
else
write_char(c);
Just another shot in the dark:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream ifstr("project.txt");
ofstream ofstr("past.txt");
if(ifstr.fail()){
cout << "error!" << endl;
} // if
bool skipOutput = false;
do
{
string word;
ifstr >> word;
if(!word.empty() && word[0] == '<')
{
skipOutput = true;
}
if(!skipOutput)
{
ofstr << word << " ";
// replicate the output to stdout
cout << word;
}
if(word[word.length()-1] != '>')
{
skipOutput = false;
}
} while(!ifstr.eof());
cout << endl << "copy complete" << endl;
ifstr.close();
ofstr.close();
//system ("pause"); Doesn't compile with my system
return 0;
} // main
If you're really just want to filter out words enclosed within '<' and '>' characters this should be sufficient. If you have more complex parsing rules for your <> tags you should elaborate your question.
I'm not sure, that this is what you wanted. Please take a look at the code!
//we create a boolean value, to know if we started skipping
bool skipStarted = false;
while(ifstr.get(c))
{
//if its a '<' and we havent started skipping jet,
//then we start skipping, and continue to the next char.
if(c=='<' && !skipStarted)
{
skipStarted = true;
continue;
}
//if its a '>' and we started skipping,
//then we finish skipping, and continue to the next char.
if(c=='>' && skipStarted)
{
skipStared = false;
ifstr.get(c);
if(c==' ')
continue;
}
//if we are skipping, then we go to the next char.
if(skipStarted)
continue;
//otherwise we simply output the character.
ofstr<<c;
}