what is the best way to parse a string in c++ [closed] - c++

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;
}

Related

Reading a file where the user has to provide some parameters [closed]

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();

How I can validate letters in c ++ with Try-catch? [closed]

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...

Preventing user from inputting certain chars in c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm quite new to c++ so please understand that my question may be silly.
I need to create a function which takes from the user a table and fills it with only specific characters. Let's say that the user needs to input his name. If the user inputs a charater from A to Z (or a to z) the character should be displayed on the screen and in that case- everything is fine. The problem is- when the user inputs a forbidden character (for instance 1-9) this shouldn't be displayed on the screen and the cursor should stay in the same position).
Do you guys know how to do this?
May be you can use this to do your job:
char ch;
while(ch = getch())
{
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
cout << ch;
}
}
This will print only [A-Z][a-z]. You can also store your required char to use further.
On Windows you can use conio.h.
Also, you can overload the istream::operator>> function to make solution more elegant and easy to use:
Complete example:
#include <iostream>
#include <conio.h>
using namespace std;
struct person_t
{
string name;
string last_name;
};
// This is the function you're looking for.
void get_filtered_string(string &str)
{
char c;
str = "";
do
{
c = _getch();
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
{
putchar(c); // 1
str.push_back(c);
}
} while (c != '\r'); // 2
}
istream &operator>>(istream &stream, person_t &person)
{
string str = "";
cout << "Enter name: ";
get_filtered_string(str);
person.name = str;
cout << endl;
cout << "Enter last name: ";
get_filtered_string(str);
person.last_name = str;
cout << endl;
return stream;
}
int main()
{
person_t person;
cin >> person;
cout << person.name.c_str() << " " << person.last_name.c_str() << endl;
return 0;
}
Output character to screen.
In Windows when you hit Enter you're introducing two characters '\r' and '\n' in that order. Thats why we check here for '\r'.

getline() gets bypassed without proper user input the first time [duplicate]

This question already has answers here:
getline not asking for input? [duplicate]
(3 answers)
Closed 9 years ago.
cout << "Type in your third message below:\n";
getline(cin, msgth);
if (msgth.length() > 0 && msgth.length() < 500) {}
else
{
system("cls");
cout << "Your message has to be between 1 and 500 characters long...";
goto prot;
}
So, whenever I get to this piece of code, it's like it automatically presses return, and "skips" the getline() function (AKA, goes to the prot label). The same thing happens further up for some reason. However, after a bit of experimenting, I've found out that when using this:
input:
if (special == 0)
{
cout << "Choose your input message below:\n";
getline(cin, inp);
if (inp.length() > 0 && inp.length() < 500) {}
else
{
system("cls");
cout << "Your message needs to be between 1 and 500 characters long\n";
goto input;
}
}
It does work the second time (with other words, after going to the input label). The difference between these two codes is that the first one has to bypass a std::cin code before getting back to getline(), while the other one doesn't.
A solution and some explaination would be gladly appreciated.
The following works for me:
#include <iostream>
#include <string>
int main() {
std::string str;
start:
std::cout << "prompt:\n";
std::getline(std::cin, str);
if (0 < str.length() && str.length() < 20) {}
else {
std::cout << "invalid.\n";
goto start;
}
std::cout << "input: \"" << str << "\"\n";
}
How is yours different from this?

Reverse each character in a string except special characters (e.g. "?") [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For example : how are you? ----> woh era uoy?
This is my code, i got it worked but the question mark is besing reversed too.
How can i make it remained intact?
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
for(int i = ch.length() - 1; i >= 0; i--)
{
cout << ch[i];
}
cout << " ";
}
return 0;
}
Your chosen input method (cin >> ch) automatically splits the input into separate words.
Like Jerry Coffin said in his answer, you have to skip over punctuation etc to find to alpha characters to swap. Roughly like this:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string ch;
while (cout << "String? " && cin >> ch)
{
cout << "Input: <<" << ch << ">>\n";
const char *bp = ch.c_str();
const char *ep = ch.c_str() + ch.length() - 1;
const char *sp = ch.c_str();
while (sp < ep)
{
while (sp < ep && (*sp != ' ' && !isalpha(*sp)))
sp++;
while (sp < ep && (*ep != ' ' && !isalpha(*ep)))
ep--;
char c = *sp;
ch[sp-bp] = *ep;
ch[ep-bp] = c;
sp++;
ep--;
}
cout << "Output: <<" << ch << ">>\n";
}
cout << endl;
return 0;
}
Sample dialogue
String? How are you?
Input: <<How>>
Output: <<woH>>
String? Input: <<are>>
Output: <<era>>
String? Input: <<you?>>
Output: <<uoy?>>
String? Pug!natious=punctuation.
Input: <<Pug!natious=punctuation.>>
Output: <<noi!tautcnu=psuoitanguP.>>
String?
You can tweak it from here. I'm far from claiming this is idiomatic C++; the use of const char * in the middle shows my C background.
Start from the beginning of the string, and scan forward until you find a letter. The scan backwards from the end until you find a letter. Swap them. Continue until the two positions meet.
Note: above I've used "letter", but all I really mean is "one of the characters that should be reversed." You haven't defined very precisely which characters should be swapped and which shouldn't, but I'm assuming you (or your teacher) has a reasonably specific definition in mind.
Try using array and scanning each letter to see if there is a question mark. If there is, move it to the last place of the array.
simple solution or hack to solve this case alone. if there are more cases comment it lets solve it together.
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
int flag = 0;
for(int i = ch.length() - 1; i >= 0; i--)
{
if(ch[i] != '?')
cout << ch[i];
else
flag = 1;
}
if(flag)
cout << "?";
else
cout << " ";
}
return 0;
}