Reading a sentence until ENTER key pressed using 2-D char array - c++

I need to read a sentence word by word until "ENTER" key is pressed. I used a do..while loop to read words until ENTER key is pressed. Please suggest me some conditions for checking ENTER key press (or) others ways for reading similar input.
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char a[100][20]={'\0'};
int i=0;
do{
cin>>a[i++];
} while( \\ Enter key is not pressed );
for(int j= 0 ; j < i ; j++)
cout<< a[j] << " ";
return 0;
}

The statement
cin>>a[i++];
blocks at the prompt already, until the ENTER key is pressed. Thus the solution is to read a single line at once (using std::getline()), and parse the words from it in a separate step.
As your question is tagged c++, you can do the following:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::string sentence;
std::cout << "Enter a sentence please: "; std::cout.flush();
std::getline(std::cin,sentence);
std::istringstream iss(sentence);
std::vector<std::string> words;
std::string word;
while(iss >> word) {
words.push_back(word);
}
for(std::vector<std::string>::const_iterator it = words.begin();
it != words.end();
++it) {
std::cout << *it << ' ';
}
std::cout << std::endl; return 0;
}
See the fully working demo please.
As an improvement the current standard provides an even simpler syntax for the for() loop:
for(auto word : words) {
std::cout << word << ' ';
}

while (cin.peek() != '\n') {
cin >> a[i++];
}

First, I must say that πάντα ῥεῖ's solution is better.
But it might be to much for you if, you are beginner.
Besides, I think you want in 2-D array, not vectors.
#include<iostream>
#include<string.h>
using namespace std;
int main(){
/*
All of this is simplified.
For example there are no check if user entered word larger than 100 chars.
And that's not all, but because of simplicity, and easy of understanding....
*/
char a[100][20]={'\0'};
char c;
char buffer[2000];
int i=0, j, k = 0;
/*
Read in advance all to way to ENTER, because on ENTER key all data is flushed to our application.
Untill user hits ENTER other chars before it are buffered.
*/
cin.getline(buffer, 2000, '\n');
do {
c = buffer[k++]; //read one char from our local buffer
j = 0;
//while we don't hit word delimiter (space), we fill current word at possition i
// and of cource while we don't reach end of sentence.
while(c != ' ' && c != '\0'){
a[i][j++] = c; //place current char to matrix
c = buffer[k++]; //and get next one
}
i++; //end of word, go to next one
//if previous 'while' stopped because we reached end of sentence, then stop.
if(c == '\0'){
break;
}
}while(i < 20);
for(j= 0 ; j < i ; j++)
cout<< a[j] << " ";
cout << endl;
return 0;
}

How about using this as your while statement
while( getchar() != '\n' );
You'll need the <stdio.h> header file for this.
See the ideone link

You can try
cin.getline(buffer, 1000);

Related

C++ I don't know how to find a word(eg.banana,sandwich) inside of a string(sentence) THE USER ENTERS the sentence and then write that word out

I've tried this but I'm stuck honestly.
I'm trying to find the first character, and then search for the ending of that substring (for eg. if the word is "sandwich" and it finds 's' that it figures out that its "sandwich") and then write out the word sandwich. And also I'm new to C++.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s, word;
char a;
cout << "Enter the sentence that you desire: ";
getline(cin, s);
cout << "Enter the letter that you want: ";
cin >> a;
for (int i = 0; i < s.length; i++)
{
if (s[i] == a)
{
if (s[i] == '\0')
{
word = s;
cout << word;
}
}
}
return 0;
}
The request is a bit foggy but given also the code you posted, i think i got a heck of what you intend to do.
The easiest (yet not necessarily the most performing one) is to use a stringstream, more precisely an istringstream.
You basically build it with a string (the one you passed from keyboard) and then you use it as if it was your cin (it acts as a normalized istream).
At that point you can iterate each word of the sentence and check the first letter.
The first character of a string is either myString[0] or myString.front(). That is up to you.
the code should look like this :
#include <iostream> //cin/cout
#include <sstream> //istringstream
using namespace std ;
int main()
{
//first of all let's get our sentence AND the character you want
cout << "insert sentence here: " ;
string sentence ;
getline(cin, sentence) ;
cout << "insert the character here: " ;
char letter ;
cin >> letter ;
//then let's create an istringstream with said sentence
istringstream sentenceStream(sentence) ;
//let's then iterate over each word
string word ;
while(sentenceStream >> word)
{
//and see if the word starts with the letter we passed by keyboard
if(word.front() == letter)
{
cout << "the word \"" << word << "\" starts with '" << letter << "'\n" ;
}
}
return 0 ;
}
Just a couple of hints:
iostream includes string already, there is no need to re-include it.
[Edit] (as pointed out by whozcraig, this does not follow the standard. guards will "negate" the double inclusion anyway, so yes, including string is not a mistake. as specified in the comment, i'm yet to find an implementation of iostream that does not include string)[/Edit]
It is good practice not to call a variable 's', or 'a': use a name
that makes it recognizable.
You can find the end of a word with std::find_if:
#include <algorithm>
#include <string>
template <typename Is>
std::string find_word(Is& stream, char needle) {
auto const nonword = [](char c) {
if ('a' <= c && c <= 'z') return false;
if ('A' <= c && c <= 'Z') return false;
if (c == '-') return false;
return true;
};
for (std::string w; stream >> w;) {
if (w.size() && w[0] == needle) {
auto const last = std::find_if(std::begin(w),std::end(w),nonword);
return std::string(std::begin(w),last);
}
}
return "";
}
This takes any stream as argument, including std::cin, and can be invoked like this:
std::cout << find_word(std::cin,'w') << "\n";
It is important to specifically find the last character in each chunk handed you by the stream because the streams will only cut along whitespace by default. So if you enter a sentence:
Hello world!
You want the end of the word to be 'd', not '!'.

find a certain word in sentence in c++

I want to write a program that finds a word that the user entered I think my solution is right but when I Run it, the program shows nothing in the console
anybody can fix it?
int main()
{
char sen[200],del[200],maybedel[200];
cout<<"enter sentence :"<<endl;
cin.getline(sen,200);
cout<<"which word do you want to delete ?";
cin.getline(del,200);
int len = strlen(sen);
for(int i=0;i<=len;i++)
{
if(sen[i]==' ')
{
for(int j=i;j<=len;j++)
if(sen[j]==' ' || sen[j]=='\0')
for(int k=i+1,t=0;k<j;k++,t++)
maybedel[t]=sen[k];
if(maybedel==del)
cout<<maybedel;
}
}
return 0;
}
The line if(sen[i]==' '), line 12 of your code , prevents code from entering the block unless the sentence begins with (' ')!
I changed the code a bit and now it works fine.
char sen[200], del[200], maybedel[200];
cout << "enter sentence :" << endl;
cin.getline(sen, 200);
cout << "which word do you want to delete ?" << endl;
cin.getline(del, 200);
int len = strlen(sen);
int t = 0;
for(int i = 0; i <= len; i++) {
if(sen[i] == ' ' || sen[i] == '\0') {
maybedel[t] = '\0';
t = 0;
if(strcmp(del,maybedel)==0) {
cout << maybedel << endl;
}
}
else
{
maybedel[t] = sen[i];
t++;
}
}
The major reason for no output is
if (maybedel == del) // <<< this will *never* be true
cout << maybedel; // will never run
Since comparing "strings" in arrays needs help from std::strcmp(maybedel,del) == 0 would be better.
UPDATE:
Another attack method is to avoid raw loops and utilize the STL to your favor. Here's a more robust solution:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
int main() {
cout << "enter sentence :\n";
string sen;
if (!getline(cin, sen)) throw std::runtime_error("Unable to read sentence");
cout << "which word do you want to delete ? ";
string del;
if (!(cin >> del)) throw std::runtime_error("Unable to read delete word");
istringstream stream_sen(sen);
vector<string> arrayofkeptwords;
remove_copy_if(istream_iterator<string>(stream_sen), istream_iterator<string>(),
back_inserter(arrayofkeptwords),
[&del](auto const &maybedel) { return maybedel == del; });
copy(begin(arrayofkeptwords), end(arrayofkeptwords),
ostream_iterator<string>(cout, " "));
cout << '\n';
}

How do you flush the contents of `std::cin` before an additional read from it?

I am trying to read a single character multiple times. The catch is that I need to prevent user errors. So for example:
char arr[10];
for(int i = 0; i < 10; i++)
{
cin.get(arr[i]);
}
Where the inputs should be something like a, b, c, d, .... But if someone were to enter ab for the first entry I want to capture the a and then ignore the b. I know about cin.ignore however I don't know how I would go about ignoring an arbitrary number of alphanumeric characters or symbols considering that I want to ignore a potentially unlimited number of characters and then stop ignoring and read again.
How can I either ignore an arbitrary number of characters and then stop ignoring or how can I actually flush the buffer for cin.
Most input is line feed so if you want to ignore all characters in the input stream until you hit a newline then you could use:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Since we ignore up to the streamsize there should not be an extra content in the input buffer.
If you want user to hit enter after each symbol, then code could be as simple as this:
char arr[10];
for(int i = 0; i < 10; )
{
std::string line;
std::getline( std::cin, line );
// check that line is not empty
if( line.empty() ) {
std::cout << "missing input" << std::endl;
continue;
}
arr[i++] = line[0]; // get only first symbol and ignore the rest
}
if you have something else in mind, I am afraid that will not work with std::cin - you do not see any input until user presses enter. In that case you would have to use OS specific functions to get unbuffered input.
The following is the code that you want, if your inputing like this a 'enter' b 'enter' c 'enter' etc...
#include <iostream>
#include <string>
using namespace std;
int main() {
char arr[10];
string line;
for (int i = 0; i < 10; i++)
{
getline(cin, line);
arr[i] = line[0];
cout << endl << "Here is the Char: " << arr[i] << endl;
}
return 0;
}
BUT if you enter input like this in one line: a,b,c,d,e,f,g,h,i,j 'enter' then you want the following code:
#include <iostream>
#include <string>
using namespace std;
int main() {
char arr[10];
string line;
int i = 0;
size_t end;
getline(cin, line);
end = 0;
int counter = 0;
if (line != "") {
while (end != string::npos && counter < 10) {
if (counter == 0) {
arr[counter] = line[0];
}
else {
end = line.find(",", end + 1);
arr[counter] = line[end + 1];
}
counter++;
}
}
for (int i = 0; i < 10; i++) {
cout << endl << "Here is the Char: " << arr[i] << endl;
}
return 0;
}

Representing a User Entered String Diagonally

I am currently a bit stuck. I need to write a program in c++ that allows a user to enter a string (any length with any amount of spaces) and the program then need's to represent this diagonally. I can get it to work but only for the first word and not for any word's entered after the first word. Below you can find my code.
Thanks People!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string strHello;
cin >> strHello;
for(int k = 0; k < strHello.length(); k++)
{
for (int x = 0; x <= k; x++)
{
if (k==x)
cout << strHello.at(x);
else
cout << " ";
}
cout << '\n';
}
return 0;
}
Yes the problem is as others have mentioned, that >> operator stops reading at the first white space character found, so std::getline() does the job, and aditionally you don't need the nested loops, take a look at this
#include <iostream>
#include <string>
using namespace std;
int
main(void)
{
string text;
string spaces;
getline(cin, text);
for (int k = 0 ; k < text.length() ; ++k)
cout << (spaces += ' ') << text.at(k) << endl;
return 0;
}
The problem is in your input, not your output. The problem is that you only call
cin >> strHello;
once. This reads in only the first sequence of non-white-space characters that are delimited by any amount of {white-space, begin of input, end of input}. So, your program will only read in the first such sequence of any input and discards any white space in the input.
Use getline, e.g
std::getline(cin, strHello);
cin will read only the first string it see before white space. e.g. "hello world" will have only hello in strHello.
cin >> will break up the input string at whitespace characters. You should use getline() instead.
getline(cin,strHello);
Here is a program that I think will help:
#include <iostream>
#include <string>
#define MAX_LEN 100
using namespace std;
int main()
{
char strHello[MAX_LEN] = { 0 };
cout << "Enter a string";
cin.getline(strHello, MAX_LEN);
for (int k = 0; k < sizeof(strHello); k++){
for (int x = 0; x <= k; x++){
if (k == x)
cout << strHello[x];
else
cout << " ";
}
cout << '\n';
}
return 0;
}

C++ checking if a string index is a digit

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str, temp;
cout << "enter string: \n";
getline (cin, str);
vector<int> vec;
int num;
cout << "str size is " << str.size() <<endl;
for (int j=0; j < str.size(); j++)
{
int num2= str.size()-1;
if (isdigit(str[j]))
{
temp+= str[j];
num = atoi(temp.c_str());
if (num2 ==j)
vec.push_back(num);
}
else if (str[j] == ',')
{
num = atoi(temp.c_str());
temp.clear();
vec.push_back(num);
}
else
{
cout << "error\n";
temp.clear();
}
}
for (int k=0; k < vec.size(); k++)
cout << vec[k] <<endl;
}
I'm trying to make a program to where it reads in a string such as
5,6,7,8,11,120
and it'll separate the numbers from the commas, but if anything else is in the string it'll report it as an error. For example, if it was 5,6,f or 5, ,3 (space).
My program is not working though and I think it has something to do with when I am checking if it's a digit with the (isdigit) function. as it is counting fs, sds, xdx as a digit. Any idea how I can fix this?
EDIT:
I've updated my code but I am still coming across problems. If I type in for example: 3,2,f it's saying that f is 0. How can I fix this?
Use
std::getline(std::cin, str);
instead of
cin >> str;
Your string is getting tokenized to just the first "word". getline() reads in the whole line into str.
Run the program in debug, and set a breakpoint at
cout << "error\n";
If it doesn't halt there for non-digit input, your compiler is buggy.
Your program, as far as I can tell, isn't. (apart from that it doesn't capture the last element, unless you terminate the input with ',')
Also check that you don't include any third-party header that redefines isdigit
Use STL function instead C-style function.
Look at http://www.cplusplus.com/reference/string/stod/