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 5 years ago.
Improve this question
OK so i know the question is a bit confusing (dont downvote right away, let me explain...)
I have a text file like this:
dim
coins
oponent
I want to read this text file but while reading it, ask the user for specific responses, for example:
"reads line with the word dim" -> asks user the dimensions -> next line -> "reads line with coins" -> asks user how many coins and so forth until the EOF.
Is there anyway to do this? if yes, can you show me how?
Thanks and plz dont downvote, just tell me what's wrong and i will edit the post..
EDIT: This is the way i'm reading the file and asking the user input
void LeitorFich::lerFicheiro(string nomeFich)
{
int i, j, t;
string linha, nome, nome1;
ifstream fich(nomeFich);
while(getline(fich, linha))
{
istringstream iss(linha);
iss >> nome;
if(nome == "dim")
{
cout << nome << " ";
iss >> i >> j;
}
}
cin.get();
fich.close();
}
A simple example will look like this:
Consider I have a file called "test.txt" which contains the very content as yours
string sLine;
ifstream inFile("test.txt");
int Dim1, Dim2, coins, oponent;
while(inFile >> sLine ){
if("dim" == sLine){
std::cout << "Dim1: ";
std::cin >> Dim1;
std::cout << std::endl;
std::cout << "Dim2: ";
std::cin >> Dim2;
std::cout << std::endl;
}
else
if("coins" == sLine){
std::cout << "coins: ";
std::cin >> coins;
}
else
if("oponent" == sLine){
std::cout << "oponent: ";
std::cin >> oponent;
}
}
inFile.close();
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a school task that I need to complete. I'm an entry level programmer, really just for some school stuff so it isn't that complicated. I just need to find out, what's the easiest way to cover all of the answers. Here is my code.
float e,d, m,n,d, no;
cout << "Enter the numerator of the first radian or if it doesn't have one, type no: ";
cin >> e;
cout << "Enter the denominator of the first radian or if it doesn't have one, type no: ";
cin >> m;
cout << "Enter the numerator of the second radian or if it doesn't have one, type no: ";
cin >> d;
cout << "Enter the denominator of the second radian or if it doesn't have one, type no: ";
cin >> n;
Then I need to solve an equation with them.
I would like it to work in every possible way but it's diffcult to cover all of the possible answers. Any tips, how should I start. I know it's probably confusing, I don't know if it's correct or not.
How to read number or some text from stream.
When you read a number, but something else is encounter, stream is set int invalid state (failbit flag is set). So to handle case first you have to clear error flag and then read a string.
Since you are expecting "no" text so if something else is encounter then failbit flag can be restored.
std::istream& read_value_or_NO(std::istream& in, std::optional<double>& x)
{
double y;
if (in >> y) {
x = y;
return in;
}
std::string s;
in.clear();
x = {};
if (in >> s && s == "no") {
return in;
}
in.setstate(std::ios::failbit); // error if it is not "no" string
return in;
}
https://godbolt.org/z/rPdTTMbvT
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 6 years ago.
Improve this question
I would like to improve the code below. I would like to use try-catch statement to validate the input letters. An error message should be printed in case the user inputs an invalid letter.
I have two methods: showMenu and selectOperation.
The methods:
//Show Operations in menu
void showMenu()
{
cout << " Select an option: \n\n"
<< "1 = Register new customers \n"
<< "2 = Register new products \n"
<< "3 = Add Product Existence \n"
<< "4 = Register a new purchase \n"
<< "0 = Exit \n\n";
}
//Select an Operation from menu
int selectOperation()
{
int selectedOperation = 0;
do
{
showMenu();
cin >> selectedOperation;
if ((selectedOperation < 0) || (selectedOperation > 4))
{
cout << "\n You have selected an invalid option"
<< "...Try again \n";
system("pause");
system("cls");
}
} while ((selectedOperation < 0) || (selectedOperation > 4));
return selectedOperation;
}
How should I do this?
You usually don't want to get and handle exceptions for invalid input.
Using exceptions to control regular flow of a program is a well known design flaw/anti pattern.
The idiomatic way is to check the input streams state:
// is true for non integer input and numbers outside the valid range
while(!(cin>>selectedOperation)) {
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
The exception variant looks like this (way more complicated and less concise IMO):
cin.exceptions(std::ifstream::failbit);
bool validInput;
do {
try {
validInput = true;
cin>>selectedOperation)
}
catch (std::ios_base::failure &fail) {
validInput = false;
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
} while (!validInput);
You have to clear the input stream in any way from fail() state.
You could also do this with a if else if statement...
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 7 years ago.
Improve this question
my code only saves the last line for eg if i enter 1 abc then press enter and then type 2 def then only 2 def is saved in txt file.
here is my code :-
int main()
{
ofstream rankings;
rankings.open("rankings.txt");
cout << "Enter rank of the Student <space> followed by Name\n"
"Press Ctrl+Z to quit"<< endl;
int rank;
string name;
while (cin >> rank >> name);
{
rankings << rank << ' ' << name << endl;
}
rankings.close();
return 0;
}
You have a superfluous semicolon after your while loop:
while (cin >> rank >> name);
// ^
This will just open a new block in the code afterwards, and leave you with the least values input.
To fix change your loop to
while (cin >> rank >> name) {
rankings << rank << ' ' << name << endl;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
How best to parse the following string in c++:
the input is a string, for example:
(someString1 45)(someString2 2432)(anotherString 55) // .... etc.
of course we are interested with the string-name and value..
our goal is to save the string and value in a map.
is there a automatic way to get the string inside the brackets ?
thank you,
A simple solution if your strings don't contain whitespace:
#include <iostream>
#include <string>
int main()
{
char c1, c2;
int n;
std::string s;
while (std::cin >> c1 >> s >> n >> c2 && c1 == '(' && c2 == ')')
{
std::cout << "Parse item: s = '" << s << "', number = " << n << "\n";
}
}
This method only works on correct input and has no way of recovering mid-way. If you need that, you can build something somewhat more elaborate using getline with ) as the separator.
The following will do the trick:
string some; int n;
string s = "(someString1 45)(someString2 2432)(anotherString 55)";
stringstream sst(s); // to parse the string
while (sst.get() == '(' && sst >> some >> n && sst.get()==')') {
cout << some << "," << n << endl;
}
This loop will not try to read some string and n if the open brace is not present.
A slight change could even allow to safely parse further input string if you'd expect something to follow the list of entries between braces:
string s = "(someString1 45)(someString2 2432)(anotherString 55)thats the rest";
...
while (sst.get() == '(') { // open brace to process
if (sst >> some >> n && sst.get() == ')')
cout << some << "," << n << endl; // succesful parse of elements
else {
cout << "Wrong format !!\n"; // something failed
if (!sst.fail()) sst.setf(ios::failbit); // case of missing closing brace
}
}
if (sst) { // if nothing failed, we are here because open brace was missing and there is still input
sst.unget(); // ready to parse the rest, including the char that was checked to be a brace
string rest;
getline(sst, rest);
cout << "The braces are followed by: " << rest << endl;
}
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 8 years ago.
Improve this question
I'm just a beginner and trying out some code that my teacher taught us to use and things from the textbook.
This program is designed to be for the user to enter in their name and enter in the password as what the system asks them to put down.
Can somebody explain to me why this loop keeps looping itself infinitely when else is triggered?
Also, what does the cin.ignore do to the memory of the char name? Why is 80 better than 20?
AND, why aren't the random numbers actually random? Every time I run it, the numbers are the same.
Thank you all so much!
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
char name[20];
int pwd, rand1, rand2;
for (int i=0;i<1; i++)
{
cout<<"Name: ";
cin.get(name, 20);
cin.ignore(80, '\n');
cout<<endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand()%6);
cout<<"Password: "<<rand1<<"*"<<rand2<<"= ";
cin>>pwd;
if(pwd == rand1*rand2)
{
cout<<endl<<"Welcome to our main page, "<<name<<"."<<endl;
}
else
{
cout<<"Wrong password, type again." <<endl;
i--;
}
}
return 0;
}
First up formatting of code will help you understand better.
Also avoid using namespace std, its bad practice and clutters the global scope with names. Instead use using std::xxxx if you dont want to write std::cout, std::cin, etc every time.
Reformatted code:
#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;
using std::endl;
int main ()
{
char name[20];
int pwd, rand1, rand2;
for (int i = 0; i < 1; i++) {
cout << "Name: ";
cin.get(name, 20);
cin.ignore();
cout << endl;
srand(rand() % 1000);
rand1 = (rand() % 21);
rand2 = (rand() % 6);
cout << "Password: " << rand1 << "*" << rand2 << "= ";
cin >> pwd;
cin.ignore();
if(pwd == rand1*rand2) {
cout << endl << "Welcome to our main page, " << name << "." << endl;
} else {
cout << "Wrong password, type again." << endl;
i--;
}
}
return 0;
}
Secondly as you can see in the above code the line cin.ignore(); has been added after cin >> pwd. Before your code was getting cin >> name, leaving '\n' in the input, ignoring '\n', getting cin >> pwd, leaving '\n' in input, looping and reading input as empty with a '\n', leaving another '\n' in input, first '\n' is removed by ci.ignore(), second '\n' read by cin >> pwd, ... etc. Or at least this is how I understand it.
Somebody has answered the first question:Because when you i--, the i in the for loop keeps decreasing and then increasing.-By Gasim
Then, if your input is longer than 20, the program may stop. So you need cin.ignore(80, '\n') to ignore the excess input. The number 80 is just a big number. You can replace it with another number-only if it's big enough.
You are supposed to use srand with time. srand(time(null)) may help.