c++ count whitespaces between numbers (not strings) - c++

So I have a program that takes in integers from user and puts them in a vector and displays them. however, I want to be able to show the total number of whitespaces between the numbers I put while inputting the numbers also.. I had a look online but couldn't find anything that would work for ints or chars.. I cant use strings or getline right now so idk what to do..
here is my code
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a,count;
vector<int> numbers;
while(cin>>a)
{
numbers.push_back(a);
// count whitespaces??
}
for(int i=0;i<numbers.size();i++)
{
cout<<numbers[i]<<endl;
}
return 0;
}
so if the input is 1(space)2(space)(space)3(space)
i want to be able to calculate the total spaces in between so in this case count would be 4

Try getline():
string str;
getline(cin,str);
and then count whitespace in str:
int wc = 0;
for (auto c: str) wc += (c == ' ');
cout << wc << endl;

Related

Finding and changing repeated letters in a word

I'm trying to create logic that goes through the word and tries to find if there are letters, that are used more than once. If a letter repeats, then change it to "1", if it's not then change it to "2". Example: Radar - 11211, Amazon - 121222, karate - 212122.
Specific problem is that if I use for(), each letter compares to the last one. Also I don't understand how can I check last letter by using for().
Last letter is always 2.
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{ string word;
char bracket1('1');
char bracket2('2');
cout << "Write your word: ";
cin >> word;
for (int i = 0; i < word.length(); ++i)
{
char let1 = word[i];
char let2 = word[i+1];
if (let1 == let2)
{ word[i] = bracket1;}
else
{ word[i] = bracket2; }
} cout << word;
}
Example: test returns 1e22 instead of 1221
You have undefined behavior in your program when wrote word[i+1]; inside the for loop. This is because you're going out of bounds for the last value of i by using i+1.
One possible way to solve this would be to use std::map as shown below. In the program given std::tolower is used because you want capital and small letters to be treated the same.
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
std::string word;
std::cout << "Write your word: ";
std::getline(std::cin, word);
//print out the word before replacing with 1 and 2
std::cout<<"Before transformation: "<<word<<std::endl;
std::map<char, int> charCount; //this map will keep count of the repeating characters
//iterate through each character in the input word and populate the map
for(char &c: word)
{
charCount[std::tolower(c)]++;//increment the value by 1
}
//replace the repeating characters by 1 and non-repeating by 2
for(char &c: word)
{
if(charCount.at(std::tolower(c)) > 1)
{
c = '1';
}
else
{
c = '2';
}
}
//print out the word after transformation
std::cout<<"After transformation: "<<word<<std::endl;
return 0;
}
The output of the program can be seen here.
Output for the input Amazon is:
Write your word: Amazon
Before transformation: Amazon
After transformation: 121222

How to iterate over the words of a sentence in C++?

My input is "Hello World" and my targeted output is "olleH dlroW".
So my idea is to get the sentence into a variable and then loop over the words in the sentence, reverse each of them and finally concatenate them into a new variable.
My question is: how to iterate over the words of the sentence?
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
string reverseword(string word)
{
string rword;
int size = word.length();
while (size >= 0)
{
rword+= word[size];
size = size -1;
}
return rword;
}
int main()
{
string sentence;
cout<<"Enter the word/sentence to be reversed: ";
cin >> sentence;
string rsentence;
// for every word in the sentence do
{
rword = reverseword(word);
rsentence = rsentence + " " + rword;
}
cout<<rword;
return 0;
}
Before you can iterate over words in a sentence, you need to read a sentence from input. This line
cin >> sentence;
reads the first word of a sentence, not the whole sentence. Use getline instead:
std::getline(std::cin, sentence);
With sentence in memory, you can iterate it word-by-word using istream_iterator as follows:
stringstream ss(sentence);
for (auto w = istream_iterator<string>(ss) ; w != istream_iterator<string>() ; w++) {
string &word = *w;
...
}
Demo.
Here is a solution that uses find and reverse to achieve the output:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string sentence;
std::getline(std::cin, sentence);
std::cout << sentence << std::endl;
size_t cpos = 0;
size_t npos = 0;
while((npos = sentence.find(' ', cpos)) != std::string::npos)
{
std::reverse(sentence.begin() + cpos, sentence.begin() + npos);
cpos = npos + 1;
}
std::reverse(sentence.begin() + cpos, sentence.end());
std::cout << sentence << std::endl;
return 0;
}
Input:
this is a nice day
Output:
this is a nice day
siht si a ecin yad
for(short i=0;i<sentence.length();i++){
if(sentence[i] == ' '){
counter++;
i++;
}
words[counter] += sentence[i];
}
Note the above loop to split the sentence with space and store it to a string array, words[]
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
string reverseword(string word) // function to reverse a word
{
string rword;
int size = word.length();
while (size >= 0)
{
rword+= word[size];
size = size -1;
}
return rword;
}
int main()
{
string sentence;
cout << "Enter the word/sentence to be reversed: ";
std::getline(std::cin, sentence);
string rsentence;
string words[100];
string rword;
short counter = 0;
for(short i=0; i<sentence.length(); i++){ // looping till ' ' and adding each word to string array words
if(sentence[i] == ' '){
counter++;
i++;
}
words[counter] += sentence[i];
}
for(int i = 0; i <= counter; i++) // calling reverse function for each words
{
rword = reverseword(words[i]);
rsentence = rsentence + " " + rword; // concatenating reversed words
}
cout << rsentence; // show reversed word
return 0;
}
I have corrected the code. Hope this helps...!!
NB : You were using cin to read space seperated string that is not possible. You must use std::getline(std::cin, sentence) to read space separated strings.
You can also use std::reverse() to reverse a string
Please refer to Most elegant way to split a string?
to split your sentence into tokens(words)
then, iterate over the new list of words to perform any operation
An answers above gives a way to convert your input to words, i.e., cin >> sentence returns a "word" (so, just call it repeatedly).
However, this brings up the question of what is a "word". You would like to translate a computer construct - string of characters - into a more complex form - words. So, you must define what you mean when you want words. It can be as simple as "space" separated substrings or your string - then use the split function, or read your string a word at a time (cin >> word)
Or you may have more stringent requirements, like they can't include punctuation (like a period at the end of a sentence) or numbers. Then think about using Regex and word patterns (like, "\w+").
Or you may want "real" words like you would find in a dictionary. Then you need to take into account your locale, parse your input into chunks (using split, Regex, or something), and look up each chunk in a human language dictionary.
In other words, "word" parsing is only as simple or complex as your requirements are.
With Boost you could use the boost::split function:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>
int main()
{
std::string sentence = "Hello world";
std::vector<std::string> words;
boost::split(words, sentence, boost::is_any_of(" "));
std::string rsentence;
for (std::string word : words) // Iterate by value to keep the original data.
{
std::reverse(word.begin(), word.end());
rsentence += word + " "; // Add the separator again.
}
boost::trim(rsentence); // Remove the last space.
std::cout << rsentence << std::endl;
return 0;
}
This answer is my humble contribution to the fight against global warming.
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
int main()
{
std::string sentence;
while (std::getline(std::cin, sentence))
{
auto ws = sentence.begin();
while (ws != sentence.end())
{
while (std::isspace(*ws)) ++ws;
auto we = ws;
while (we != sentence.end() && !std::isspace(*we)) ++we;
std::reverse(ws, we);
ws = we;
}
std::cout << sentence << "\n";
}
}
This assumes "word" is defined as "a sequence of non-whitespace characters". It is easy to substitute a different character class instead of "non-whitespace", e.g. for alphanumeric characters use std::isalnum. A definition that reflects the real-world notion of word as e.g. used in natural language sciences is far far beyond the scope of this answer.

Input numbers by keyboard into array but only 1 line

Is there any way to enter numbers (seperated by spaces) on a single line into an array ? I mean, I used to write like this:
First, I entered sizeofarray. Then, I used [for] loop to enter each number into each element. In this method, I had to press enter for each time
So what I want is:
First, enter sizeofarray. Then, on a single line, enter all numbers for all elements, each of it seperated by a space
Ex: 7, enter
1 5 35 26 5 69 8, enter
So that all numbers are stored into elements dedicated.
I know my English is not good and I'm not a good coder. So please explain it easy. Thanks :D
I don't know why everyone is trying to do it in String way..
it's simple that C++ std::cin can get it so easy
int main (){
int a[1000],sizeOfA;
cin>>sizeOfA;
for (int i=0;i<sizeOfA;i++)
cin>>a[i];
If you are going to enter all numbers in a single line, then it is completely unnecessary to begin by entering the number of numbers that will follow.
You are going to need to read the entire line into a string, (char[]) and then parse that string to find substrings separated by spaces, and then you are going to need to parse each substring into a number.
Precisely how to do this, we won't tell, because stackoverflow is not about having others do your homework for you.
Read in the input as a string, then split by spaces to get the individual numbers:
int main()
{
using namespace std;
int* nums;
int size;
cout << "Enter size of array";
cin >> size;
nums = new int[size];
string input;
cout << "Enter numbers, separated by single space:\n";
getline(cin, input);
istringstream iss(input);
string s;
int i = 0;
while (getline(iss, s, ' ') && i < size) {
int num = atoi(s.c_str());
nums[i] = num;
printf("%d\n", num);
++i;
}
return 0;
}
the most optimal and safe way is use containers, iterators and streams. If 'istream_iterator ' extract from the stream value other than 'int', it will be equal to 'end', so reading from the stream being to the first non-int, or until the end
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
int main()
{
using namespace std;
size_t size = 0;
cin >> size;
cin.ignore();
string buffer;
getline(cin, buffer);
stringstream ss(buffer);
istream_iterator<int> iter(ss);
istream_iterator<int> end;
vector<int> vec;
vec.reserve(size);
for (size_t i = 0; i < size && iter != end; ++i, ++iter)
{
vec.push_back(*iter);
}
}

How can I get the number of characters from an input string?

I am trying to count the number of characters in a string that is provided by the user. I know I can use string::length() and string::size() but when a space is encountered, the count is stopped. For example, say the user inputs "Bob Builder", the count should be 10 but what my code would display would be 3. Also I am trying to do this without using a character array. Any suggestions? An explanation would also greatly help.
int main()
{
string Name;
cin>>Name;
cout << name(Name);
return 0;
}
int name(string a)
{
int numChar;
/*for (int i=0; a[i] != '\0';i++)
{
if (!isspace(a[i]))
numChar++;
}*/
numChar=a.length();
return numChar;
}
How yu know when input is over?
If you want to read until end of line then this is a possible solution:
std::string line ;
std::cin.getline(line) ;
line.length() ;
You have to use getline() instead of cin to get all line up to newline. cin reads input up to whitespace.
std::getline (std::cin,Name);
If you use using namespace std;
getline (cin,Name);
If you want to count the input string excluding spaces, the code snippet helps you.
#include <algorithm>
#include <string>
int main()
{
std::string s = "Hello there, world!";
std::cout << std::count( s.begin(), s.end(), ' ' ) << std::endl;
}

String not getting stored in vector?

#include <iostream>
#include <vector>
using namespace std;
int main()
{
string n, m;
vector <string> dingdong;
cin >> n;
dingdong.push_back(n);
cin >> m;
dingdong.push_back(m);
for (int i = 0; i <2; i ++) {
cout << dingdong[i];
}
return 0;
}
When I run the program and I input "hay sombody there" and hit enter. The program prints "haysombody." So I figured if I increase 'i' to 3 the program will print "haysombodythere" but no, main just crashes. why is this happening and how do I make it so that the entire strings (including the spaces) get stored?
"why is this happening and how do I make it so that the entire strings (including the spaces) get stored?"
To get more than a single word from the input you should use
std::getline(cin,n);
instead of
std::cin >> n;
White spaces are used as delimiters by default, so each call of std::istream's operator>> will just store the text read up to the next white space character.
See a fully fixed version of your program here please.
Also if you really want to read into the vector word by word, you use a loop doing so
string word;
vector <string> dingdong;
while(cin >> word) {
if(word.empty) {
break;
}
dingdong.push_back(word);
}
and print out like
for (int i = 0; i < dingdong.size(); ++i) {
cout << dingdong[i];
}