C++ input multiple words to string - c++

I've tried using getline(), but the problem is that i have this in loop, and the program simply doesn't stop to get the inputs like it normally does when using cin.
Here's how my code looks like:
for (int i=0; i<value; i++){
cout<<endl<<"what are You saerching for?";
getline(cin, searchFor[i]);
cout<<"How it should be changed?";
getline(cin, changeTo[i]);
}
It works normally using cin, but that way i can't get more than 1 word to the table (both tables are strings).

You could simply use scanf to do this.
Here is a little example that ask the user to type text, then print the user entry on "enter" key press
#include <iostream>
#include <stdio.h>
int main(int argc, char **argv){
char buf[2048];
std::cout << "enter something" << std::endl;
scanf("%[^\t\n]", buf);
printf("Your input : %s\n", buf);
return 0;
}
Note In that example, buf is only 2048 bytes, this means that a user could enter more than 2048 caracters, and break this little code with a seg fault, be safe with strings.

Related

(c++) problem in printing words of char array string

I'm making a c++ program using string(data type) and char array. Now, the data type is printing words alright. But, I'm having some trouble with the char array. Here's the code:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[200];
string str1;
cout<<"Enter a string:\t";
getline(cin,str1);
cout<<str1 <<endl;
cout<<"enter second string:\t";
cin>>str;
cin.get(str,200);
cout<<str;
}
code output
As, you can see in the output, the data type string is printing the words fine. But, the char array is missing the first word. Am I doing something wrong? or does the char array work in different way? Please explain. Thanks.
While you have already discovered that cin >> str; isn't required as you are simply writing again to str with cin.getline (str, sizeof str), there are a number of additional issues you should address:
1. Unless your compiler is ancient, you should #include <string>, not the C-header string.h;
2. Don't use magic-numbers in your code. If you need a constant, e.g. for the maximum number of characters in str, #define a constant or use a global enum to do the same, e.g.
#define MAXC 200 /* if you need a constant, #define one (or more) */
...
char str[MAXC]; /* don't use 'magic-number', use a constant */
That way when, and if you change the number of characters in str in the future, you don't have to pick through your entire code and change every occurrence of the magic-number, e.g. cin.get(str,200);.
3. Validate EVERY user input. Otherwise a failed input can set an error-bit on your input stream and additional attempts to read from a stream with an error-bit set can result in undefined behavior. You could do:
if (!getline(cin,str1)) { /* VALIDATE every input */
cerr << "error: input failure - str1.\n";
return 1;
}
and
if (cin.get (str, sizeof str))
cout << str << endl;
(note: there are no further attempted reads after cin.get (str, sizeof str) so guarding your use of str is sufficient)
4. Always output a newline after your final line output to ensure your program is POSIX compliant. Otherwise on many OS's you will mess up the users prompt if writing to stdout or you will create a non-POSIX compliant output file if redirecting the output to a file, e.g.
my cat has none01:22 wizard:~/dev/src-cpp/tmp/debug>
Putting it altogether, you could do something like:
#include <iostream>
#include <string> /* depending on your compiler */
#define MAXC 200 /* if you need a constant, #define one (or more) */
using namespace std;
int main (void) {
char str[MAXC]; /* don't use 'magic-number', use a constant */
string str1;
cout << "enter a string: ";
if (!getline(cin,str1)) { /* VALIDATE every input */
cerr << "error: input failure - str1.\n";
return 1;
}
cout << str1 << endl;
cout << "enter second string: ";
// cin >> str; /* not needed */
if (cin.get (str, sizeof str))
cout << str << endl;
}
Example Use/Output
$ ./bin/cin.get_getline
enter a string: my dog has fleas
my dog has fleas
enter second string: my cat has none
my cat has none
cout<<"enter second string:\t";
cin>>str;
cin.get(str,200);
here first you are trying to read the second word twice into same variable. comment one of them and try to print the content of str.
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[200];
string str1;
cout<<"Enter a string:\t";
getline(cin,str1);
cout<<str1 <<endl;
cout<<"enter second string:\t";
// cin>>str;
cin.get(str,200);
cout<<str<<endl;
}

Making array (char) 1 gives error on stdio.h

I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.
Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.

Getting a string in c++ from user, and displaying it

how do i do it??
it tried this code:
char num[10];
printf("Enter num:");
scanf_s ("%s", &num);
printf("\n%s \n", num);
ignore 'num' please..
i use VS 2013, and my only included library is "stdafx.h"
See std::getline.
In C++, don't use printf, use std::cout.
Don't use char[], use std::string.
If you selected the type of the project like console application and compile it as a C++ program then the code can look the following way
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
char s[100];
std::cout << "Enter a sentence: ";
std::cin.getline( s, sizeof( s ) );
std::cout << "You entered \"" << s << "\"\n";
return 0;
}
You don't you use the "string" in c++ instead of the char array. Its easy for operation and maintenance, plus its much more simple and efficient with so many built in algorithms.
string num ;// instead of char num[10];
cout<<"Enter num";
cin>>num;
cout<<num;
you may use printf or scanf. Thats completely ok

Why can I only xor decrypt the first two characters of my input stream?

Description:
I am writing/exploring xor encryption/decryption in c++ code for fun. I have asked previous questions on these two topics:Very long string input to xor encryption program and String input xor encryption program.
I have developed the code below that will prompt the user for a string and it is supposed to xor the string with the key in the code. The way this encryption works is that I should be able to input a string and get a encrypted string. If I run the same encrypted string through the same function I should get the original string back. See working code below.
#include <iostream>
#include <string>
using namespace std;
int main (void)
{
while (1)
{
string mystr;
cout << "What's the phrase to be Encrypted? ";
char key[11]="ABCDEFGHIJ"; //The Encryption Key, for now its generic
getline(cin, mystr);
string result;
for (int i=0; i<mystr.size(); i++) {
result.push_back(mystr[i] ^ key[i%11]);
cout << result[i];
}
cout << "\n";
}
return 0;
}
Question:
I am only able to put a string of length 2 characters into the program and be able to have an encrypted string returned back of length 2. If I put anymore characters into the program I will only get the first 2 original characters back. Why is this?
Please respond with clear explanations and or examples. Thanks
Thank you to user – DNT for suggesting this I remove the 11 from:
char key[11] = "ABCDEFGHIJ" and let the compiler figure it out.
that suggestion corrected the problem. Final code is below for anyone who may need it since this just a exploratory/fun project.
#include <iostream>
#include <string>
using namespace std;
int main (void)
{
while (1)
{
string mystr;
cout << "What's the phrase to be Encrypted? ";
char key[]="ABCDEFGHIJ"; //The Encryption Key, for now its generic
getline(cin, mystr);
string result;
for (int i=0; i<mystr.size(); i++) {
result.push_back(mystr[i] ^ key[i%11]);
cout << result[i];
}
cout << "\n";
}
return 0;
}

Reusing std::cin after EOF

The code below is for storing a group of words in a std::vector and to count how many times a particular word given by the user appears in the vector by comparing it to all the words stored in the vector.
The console does not prompt me for input at the second std::cin >> in the program below.
#include <iostream>
#include <ios>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[])
{
cout<<"enter your words followed ny EOF"<<endl;
vector<string> words;
string x;
typedef vector<string>::size_type vec_size;
vec_size size;
while (cin>>x)
{
words.push_back(x);
}
size=words.size();
cin.clear();
//now compare
cout<<"enter your word:"<<endl;
string my_word;
int count=0;
cin>>my_word; //didn't get any prompt in the console for this 'cin'
for (vec_size i=0; i<size; ++i)
{
my_word==words[i]?(++count):(count=count);
}
cout<<"Your word appeared "<<count<<" times"<<endl;
return 0;
}
The final output I get is "Your word appeared 0 times".
What is the problem with the code. Any help would be great.
The program reads the word list until end of file. So, at a terminal, you can type the EOF character (Ctrl-D on Linux, Ctrl-Z Return on Windows), but what then?
I think after resetting the stream, a terminal will continue to read. But if the program is taking input from a disk file, pipe, etc., there is no hope. End-of-file is forever.
Instead, use some sort of sentinel, or prefix it by a count. That way the first loop can run until the logical end of the list. And then it can read the word intended for the summary logic.
while (cin>>x && x != '*') // The word "*" ends the list of words
{
words.push_back(x);
}
size=words.size();
//now compare
cout<<"enter your word:"<<endl;
while (cin>>x)
{
words.push_back(x);
}
Here, you're reading until failure. So, when this loop finishes, cin is in an error state. You need to clear the error state:
cin.clear();
http://www.cplusplus.com/forum/articles/6046/
Read this as an example and probable issues !!