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;
}
Related
Write and test a program that prompts the user to input a file name and a string to test for. Search the file for every occurrence of the specified string – when the string is found, display the line that contains it. When all occurrences of the string have been found display the number of times the string appeared in the file. Hint: You may use string member function find().
Here's my code, as I stated it works with some sentences but not all, it doesn't seem to have anything to do with the length either as if I repeat a line I know works, it won't run into any errors, can someone explain?
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
void find_common_words(string, int);
vector<string> words;
int main(){
vector<string> line;
string input;
char filename[50];
ifstream inputFile;
cout << "Enter File Name:" << endl;
cin.getline(filename, 50);
inputFile.open(filename);
//TESTING IF FILE IS OPEN
if (!inputFile.is_open()){
cout << "File Wasn't Opened!" << endl;
return 0;
}
while (getline(inputFile, input)){
line.push_back(input);
}
int size_of_array = static_cast<int>(line.size());
for (int i = 0; i < size_of_array; i++){
istringstream iss(line[i]);
int word_number = 0;
do {
string word;
iss >> word;
words.push_back(word);
word_number++;
} while (iss);
}
string commonword;
cout << "Enter a word to search for (without punctuation)" << endl;
cin >> commonword;
int size_of_array2 = static_cast<int>(words.size());
find_common_words(commonword, size_of_array2);
return 0;
}
void find_common_words(string search, int sizeofarray2) {
//CONVERSION TO STRING WITHOUT PUNCTUATION
for (int i = 0; i < sizeofarray2; i++){
string temp_string = words[i];
for (int j = 0, len = temp_string.size(); j < len; j++){
if (ispunct(temp_string[j])){
temp_string.erase(j--, 1);
len = temp_string.size();
}
}
words[i] = temp_string;
}
//SEARCHING FOR SAME WORDS
int line_number = 1;
int words_found = 0;
for (int i = 0; i < sizeofarray2; i++){
if (search == words[i]){
cout << search << " Was found on line " << line_number << endl;
words_found++;
}
if (words[i].length() == 0){
line_number++;
}
}
cout << line_number - 1 << " lines checked, " << words_found << " matches " << endl;
}
Heres my input file (randomly generated):
It's a very big deal.
Carl won the spelling bee and got a trophy!
Why is your cat so big?
Do you have a big bowl I can borrow?
It's a big company.
Penguins live in the Antarctica.
Don’t be silly, you're going to the game!
What are you talking about?
He threw up in the trash can!
You're so ratchet!
But she is a good caretaker.
Tom is looking for a bigger house to live in.
I get an error with Debug Assertion
Expression c> = -1 && c < = 255
I debugged the program and WhozCraig is right. In your input text in the line
Don’t be silly, you're going to the game!
In the word "Don’t", you do not have the normal apostrophe as you have in the word "It's" or "you're"
This special character is encoded as -110 in temp_string. In the description of std::ispunct you can read:
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
-110 does not fit and causes a debug assertion error. If you cast it to unsigned char like WhozCraig proposed, it will work.
You can also fix your input file.
A very interesting and subtle error . . .
beginner here
i wrote the below in C++, it's a short program that currently takes 2 words as inputs, and outputs the same words back but the words are split into even and odd instead. I would like to be able to do this for 'T' words instead, but I can't figure it out. I would like to be able to first input the number of words that will follow, for example 10. Then to input the words and get T results back. So instead of just 2 words, an unlimited amount with the user specifying.
I need to put the below into a function and go from there sometime, but I want to learn the best technique to do so - any advice please?
Thanks!
Alex
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
Think I got it here, I was over-thinking this one
I put it in a for loop, as below - so any number of words can be input, user has to input the number of test cases at the
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++){
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
}
return 0;
}
Ultimately, you are performing the same task N times.
First, let's discuss how to store the information. Functionally, we have one string as input which yields two strings as output. std::pair (from <utility>) lets us easily represent this. But for sake of even-odd, std::array might be a better representation for us. Since we have a variable number of words as input, a variable number of std::array will be output. std::vector (from <vector>) is our friend here.
Second, let's discuss how to process the information. Using named variables for each output component does not scale, so let's switch to a fixed array (noted below as array<string,2>. By switching to a fixed array for output, addressing each split becomes a function of the loop index (index % 2). Below is a solution that generalizes on a known split size at compile time.
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}
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;
}
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);
#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/