Getting string input with a default value supplied in C++ - c++

I want to get string input from the user. At the same time, I want to supply a default string so that if the user doesn't want to change it, they can just press enter. How can that be done in C++?

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* args[])
{
const string defaultText = "Default string";
string str;
string tmp;
getline(cin, tmp);
if (!tmp.empty()) //user typed something different than Enter
str = tmp;
else //otherwise use default value
str = defaultText;
cout << str << endl;
}

You should be able to do it with the version of getline() defined in . You can use it like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin,str);
// Use str
}

Just use two strings: Default string and User_supplied string. Get the input from the user (for the user_supplied string) and do an strlen on this string to check if it has a length greater than zero. If so use the User_supplied string, else use the default string

Related

How can i store hex value in string and get the value and size of the string

I am trying to store a hex value in a string and latter retrieve it after some time, but while retrieving No value is coming size of the string is also coming 0. Sample code:
using namespace std;
int main() {
std::string s;
s.assign("\x00\x53"); // std::string s ="\x00\x53"
cout<<s.size();
}
output is coming 0
Try using \\ instead of \:
s.assign("\\x00\\x53");
Now you have:
#include <iostream>
using namespace std;
int main() {
std::string s;
s.assign("\\x00\\x53"); // std::string s ="\x00\x53"
cout << s.size() << endl;
cout << s << endl;
}
Output:
8
\x00\x53
From C++14 onwards, we have the option of using string literals, using that feature you can do this:
std::string s1 = "\x00\x53"s;
This will do what you expect and will return the correct value for size().
If you cannot use C++14 features, you need to use a string constructor that will allow you to specify the length of the string. You can do this:
std::string s1( "\x00\x53", 2);
You can see demo for both versions here.

String Stream & cli

I have this program and I want to fill the tables array with the values passed from the command line in integer form . However It string s is only being assigned argument 6 .. what is the problem ?
#include <iostream>
#include <cctype>
#include <locale>
#include <cstdlib>
#include <sstream>
#include <string>
using namespace std;
int main(int argc,char *argv[]){
int i;
int tables[100];
stringstream str;
string s;
int result;
char value;
if(argc <=1){
cout<<"NO ARGUMENTS PASSED"<<endl;
exit(0);
}
/*char value = *argv[1];
cout<<value<<endl;
str << value;
str >> s;
result = stoi(s,nullptr,10);
cout<<result<<endl;*/
for (i=1;i<argc;i++){
if(isdigit(*argv[i])){
value = *argv[i];
str<<value;
str>>s;
cout<<s<<endl;
tables[i-1] = stoi(s,nullptr,10);
}
}
}
isdigit function test if a char is a digit, so the command line
isdigit(*argv[i])
Return true is the firts character of the char* is a digit. What you want is to convert a char* to an integer, I suggest to take a look at the atoi function.
However, the string convertion for printing your result is not necessary.
The problem is that you are using stringstream in the wrong way.
By writing str >> s you are reaching eof in the stream.
To fix this, you can avoid to use stringstream and instead directly assign value to s.
If you want to use stringstream, you can reset it back to initial state after writing to s as follows:
str.str(std::string{});
str.clear();
and use it again

Function that takes a String parameter and reverses it C++

I want to create a function that takes a string parameter, reverses it and returns the reversed string. There have been some answers, but none work fully.
Here is my code:
#include <iostream>
#include <string>
using namespace std;
string revStr(string word){
string reversed = "";
if(word.size() == 0)
{
return reversed;
}
for (int i = word.length()-1; i>=0; i--){
reversed = reversed+word[i];
}
return reversed;
}
int main(){
string strin;
cout << "enter string;" << endl;
cin>> strin;
cout << revStr(strin);
}
This works only for strings that do not contain a space. When I type in Hello World, it return olleH.
basic_string::operator>>:
2) Behaves as an FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, first clears str with str.erase(), then reads characters from is and appends them to str as if by str.append(1, c), until one of the following conditions becomes true: [...]
std::isspace(c,is.getloc()) is true for the next character c in is (this whitespace character remains in the input stream).
The method you use by definition reads until a white-space, so you read only Hello into strin. You should use another method for reading like getline or stringstream.
You need to use std::getline to input strings with a space.
For reversing your std::string, consider using std::reverse from <algorithm>, although your algorithm is correct too.
Code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string strin;
cout << "enter string;" << endl;
getline(cin,strin);
reverse(strin.begin() , strin.end() );
cout << strin;
}
See, cin halts the input at any occurrence of a space or a newline character. So, to input a string with spaces, you'd have to use cin.getline() and that can be done by using the following snippet:
string S;
cin.getline(1000,'\n');
This would take input till the newline character into string S and then we just have to reverse the string, and that can be done in two ways.
Method 1:
Using std::reverse from <algorithm> header file. This function works with all containers and takes iterators as parameters.
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
string S;
getline(cin,S);
reverse(S.begin(), S.end());
return 0;
}
Method 2:
You can create your function which swaps the characters at positions equidistant from end and start, and you get what you need in O(n) time-complexity.
#include <bits/stdc++.h>
using namespace std;
string myfunc(string S)
{
int l = 0;
int r = S.size()-1;
while(l<r)
{
swap(S[l],S[r]);
l++;
r--;
}
return S;
}
int main()
{
ios_base::sync_with_stdio(false);
string S;
getline(cin,S);
S = myfunc(S);
cout<<S;
return 0;
}
What I think is you could do fine with your revStr() but you need to get a whole line input, but using cin considers space as a delimiter, hence you get only Hello out of Hello World.
Replace cin >> strin with getline(cin,strin).

File not showing last Character of string when written in file

This snippet is part of a big program. The problem I am facing is that when I write a string to the file using "write" member function, it do not show last character of string:
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
fstream file1("/users/xxxxxxx/desktop/file1.txt", ios::out);
string data;
cout << "Enter string: " << endl;
getline(cin, data);
file1.write(reinterpret_cast<char*>(&data), data.size());
//file1 << data;
file1.close();
return 0;
}
For Example: If Input String: "Hello World".
On File it will show: "Hello Worl",
But it does work fine if I input string using "file1 << data". Please help me in this
file1.write(reinterpret_cast<char*>(&data), data.size());
Don't do this, you are writing the string object itself to the file. if you really want to use write you have to get a pointer to the first char that the string holds, like this:
file1.write(data.data(), data.size());
Just use the << operator.
Why would you cast the address of a string into a char*? This isn't a meaningful conversion--you are casting a std::basic_string<char>* to char*. I suspect you want to treat string as char* since write accepts const char* as parameter. You can access the character sequence stored in your data by doing data.c_str().

Random ascii char's appearing

I was trying to write a program that stores the message in a string backwards into a character array, and whenever I run it sometimes it successfully writes it backwards but other times it will add random characters to the end like this:
input: write this backwards
sdrawkcab siht etirwˇ
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
for(int spot = 0; howLong >= 0; howLong--)
{
reverse[spot] = message.at(howLong);
spot++;
}
cout << reverse;
return 0;
}
The buffer reverse needs to be message.length() + 1 in length so that it can store a null termination byte. (And the null termination byte needs to be placed in the last position in that buffer.)
Since you can't declare an array with a length that is only known at runtime, you have to use a container instead.
std::vector<char> reverse(message.length());
Or better, use std::string. The STL also offers some nice functions to you, for example building the reversed string in the constructor call:
std::string reverse(message.rbegin(), message.rend();
Instead of reversing into a character buffer, you should build a new string. It's easier and less prone to bugs.
string reverse;
for(howlong; howLong >= 0; howLong--)
{
reverse.push_back(message.at(howLong));
}
Use a proper C++ solution.
Inline reverse the message:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message;
getline(cin, message);
//inline reverse the message
reverse(message.begin(),message.end());
//print the reversed message:
cout << message << endl;
return 0;
}
Reverse a copy of the message string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message, reversed_message;
getline(cin, message);
//reverse message
reversed_message = message;
reverse(reversed_message.begin(), reversed_message.end());
//print the reversed message:
cout << reversed_message << endl;
return 0;
}
If you really need to save the reversed string in a C string, you can do it:
char *msg = (char *)message.c_str();
but, as a rule of thumb use C++ STL strings if you can.