How to implement a semicolon ends the input in C++? [closed] - c++

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 2 years ago.
Improve this question
How to implement a command line interface, the command must end with semicolon. Then press enter to execute. Otherwise, press enter wraps the line. If I don't descirbe it clearly, you can refer to the mysql command line.
How to implement the above in C++? For example:
If user inputs foo;bar then str = "foo". It can have some spaces in between ;.
In C++ IO I just know:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
}
I don't know how to implement other input function.

The most simple approach would be to use std::getline (as adviced in comments), but with a custom delimiter (';' in your case) like this:
string command;
while (getline(cin, command, ';')) {
// process the command there
}
However, this approach has several drawbacks and is pretty limited:
it reads until any ';' is hit. If you're going to process commands complicated enough to support string literals, then you will need more complicated parsing to handle this: echo "Hello; sample text"; exit;, as two commands, but not three;
when you hit Enter, getline will wait for more input until it sees a semicolon, but it will not insert any 'user-friendly' prompt like > to let the user know that they need to supply more input or that they forgot the semicolon at the end of command.
If you're ok to go without supporting these features, getline is quite good to go. Otherwise you'll need to parse your input lines by yourself.

I guess this is what you want to do:
#include <iostream>
int main() {
std::string command;
bool flag = true;
do
{
std::string str;
std::getline(std::cin,str);
for(int i = 0; i < str.length(); i++)
{
if(str[i] == ';')
{
str = str.substr(0,i+1);
flag = false;
}
}
command += str;
} while(flag);
}

Related

how to parse line into number and string? [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 11 months ago.
Improve this question
I would like to parse a sentence beginning with a number:
2 random sentece.
5 another one.
8 this is really long sentence.
Into int number holding the beginning number and the rest in std::string sentence. So in the first line, the parsing output will be number == 2 and sentence == "random sentence". The input is read from stdin, but the classical std::cin >> number >> sentence does'n work, since the parsing of string would end once it reaches a space. But I want to make the string beginning after the initial number to the end of line \n. So, how to do it in C++?
You can make use of std::getline and std::istringstream as shown below. In particular in the given program, std::getline is used to read line by line and std::istringstream is used to read first the integer and then the remaining sentence.
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string sentence;
int inputInt = 0;
//read line by line
while(std::cin >> inputInt && std::getline(std::cin, sentence))
{
std::cout<< inputInt <<"-----"<<sentence<<std::endl;
//do the check here
}
}
Demo

How to return a string to the main int function? [closed]

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 5 years ago.
Improve this question
Here is my code(C++) below... I am confused on how to return the username I retrieved in getusername back to the main function. Does anyone have nay tips or suggestions?
#include <iostream>
//For the strings obviously
#include <string>
using namespace std;
string getusername();
string user;
string getusername() {
user = system("echo %username% > NUL");
return user;
}
int main() {
string getname;
getname = getusername();
cout << "Hello: "<< getname << endl;
}
The return statement should work. However,
user = system("echo %username% > NUL");
is a problem. See documentation of std::system to understand what it does.
If you want the user to input the value of usre, you have two options. If you want the value of user to be without whitespace, you can use:
std::cout >> user;
If you want the value of user to contain an entire line of text, whitespace and all, use:
std::getline(std:::cout, user);
If you want to use get the value of the environment variable USERNAME, use std::getenv.
user = std::getenv("USERNAME");
From http://www.cplusplus.com/reference/cstdlib/system/
Return Value
If command is a null pointer, the function returns a non-zero value in case a command processor is available and a zero value if it is not.
If command is not a null pointer, the value returned depends on the system and library implementations, but it is generally expected to be the status code returned by the called command, if supported.
If you want to run a system command and catch the output you can use popen.
A simple example could look like this.
std::string exec(const std::string& cmd) {
std::array<char, 128> buffer;
std::string result;
std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
return result;
}
As others have already pointer out, the std::system call is not interactive, meaning you cannot read/write from/to the shell.
I have implemented a nice popen() wrapper for Posix compliant operating systems that allows users easily interact with the shell, you can check it out here.
Here is a usage example:
try {
mp::ipstream reader("ls -l");
vector<string> output;
reader >> output;
}
catch (std::runtime_error & ex) {
// Something went wrong and ex.what() will tell you what it is
}
This library contains more such wrappers and you are more than welcome to use them if they suit your needs.

Modifying specific characters in text input (C++) [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 receive text with special characters (such as á) so I have to manually search and replace each one with code (in this case "á")
I would like to have code to search and replace such instances automatically after user input. Since I'm a noob, I'll show you the code I have so far - however meager it may be.
// Text fixer
#include <iostream>
#include <fstream>
#include <string>
int main(){
string input;
cout << "Input text";
cin >> input;
// this is where I'm at a loss. How should I manipulate the variable?
cout << input;
return 0;
}
Thank you!
An easy method is to use an array of substitution strings:
std::string replacement_text[???];
The idea is that you use the incoming character as the index into the array and extract the replacement text.
For example:
replacement_text[' '] = " ";
// ...
std::string new_string = replacement_text[input_character];
Another method is to use switch and case to convert the character.
Alternative techniques are a lookup table and std::map.
The lookup table could be an array of mapping structures:
struct Entry
{
char key;
std::string replacement_text;
}
Search the table using the key field to match the incoming character. Use the replacement_text to get the replacement text.

stopword removal in C++ code [closed]

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 9 years ago.
Improve this question
can Anyone help me make the stopword to be removed..I could not.. still appear after run!
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
char filename[50]; //open file
ifstream example;
cin.getline(filename , 50);
example.open(filename);
if(!example.is_open())
{
exit(EXIT_FAILURE);
}
char word[50];
example>>word;
while (example.good()&&word!="a"&& word!="an"&&word!="be"&& word!="at"&& word!="the")
{
cout <<word<<" "; // remove stopwords
example>>word;
}
system("PAUSE");
return 0;
}
can Anyone help me make the stopword to be removed..I could not.. still appear after run!
You cannot compare C-strings with the == operator. The easiest solution to your problem will be to use std::string:
string word;
example >> word;
while (example.good() && word != "a" && word != "an" && word != "be" && word != "at" && word != "the")
{
cout << word << " "; // remove stopwords
example >> word;
}
On the other hand, this will actually not remove all, as you call it, stopwords. It will just print all words until the first “stopword” is read, and then the whole loop will stop.
The problem is that you're using C-style strings, which are fiddly to use correctly. The simplest option is to use the C++ strings library:
#include <string>
std::string word;
and the rest of your program should work as expected. This will also prevent the hideous stack-corruption bug that your program will experience if an input word is too long.
If you really want to muck around with character arrays for educational purposes, then you'll need to use the C strings library to compare them:
#include <cstring>
if (std::strcmp(word, "a") != 0 && ...)
Your code compares the address of the array containing the input word with the address of a string literal; these will never be equal.
When removing stopwords, remove not only a few of them.
In addition, you should apply the Porter algorithm to your piece of code.
The Porter Stemmer has to be applied regarding string similarity if you wanna check a filtered text.
Yes, it is in C, but only applying a few words (like your question) is not an adequate removal procedure of stopwords. The C code gives you an impression if you really wanna stem in addition to removal of stopwords. This depends on the purpose.
Have done both in 2008 to filter many text fragments. Both was relevant.
hth
A competent compiler with warnings turned on will fix your problem for you. Here's what mine said:
warning: result of comparison against a string literal is unspecified (use strncmp instead)
[-Wstring-compare]
while (example.good()&&word!="a"&& word!="an"&&word!="be"&& word!="at"&& word!="the")
^ ~~~

this code compiles on my computer and runs but not on server [closed]

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 8 years ago.
Improve this question
I wrote a C++ program using codeblocks and at the last minute I decided to use empress, the server at school that we use to do our labs, and turns out that it did not work! What does that mean? Is my program not right? Or could it be a compiler issue? I normally use linux ubuntu using codeblocks to do my programming. I tested the program using windows and it also worked. Why doesn't it run on the server?
Here is the code that I think causes the problem:
bool dictionary::insertWordsIntoDict(string fileName)
{
ifstream inp;
string word;
vector<string> vec;
inp.open(fileName.data());
if(inp.good())
{
while(!inp.eof())
{
inp>>word;
vec.push_back(word);
}
string temp;
string temp2= "#.txt";
for(int i=0 ; i<vec.size() ; i++)
{
temp = vec[i];
temp2[0] = tolower(temp[0]);
cout<<temp<<endl;
AddWord(temp.data(), temp2);
}
}//end of if statement
else
{
cout<<":( File does not exist! "<<endl;
return failure;
}
}// end of function insert words
while(!inp.eof()) is not a good way to read from a file. In particular, if it cannot read for some reason other than EOF, the condition will never be false, and your loop will run forever.
The correct way to write this kind of loop is:
while(inp >> word)
{
vec.push_back(word);
}
Here, inp >> word will evaluate to false if word could not be read from the input stream for any reason.
I can't be sure this is your problem without more details, but it can't hurt.
Well there is at least one issue, you are using eof in your loop condition, you should modify like so:
while( inp >> word)
{
vec.push_back(word);
}
This previous thread covers why Why is iostream::eof inside a loop condition considered wrong?.