Unexpected return from cin.getline() in C++ - c++

I have this problem that when I use getline() function to input a char array it also inserts other characters, that are not constant and change every time I run the program.
I do realize it is most likely because of some kind of overflow happening, and it just takes numbers from the RAM.
But is there a possibility to fix that?
(Program is supposed to reverse a string and remove any non-letters, excluding spaces)
Here is my program:
#include <iostream>
#include <ctype.h>
#include <string>
using namespace std;
int main() {
string decoded = "";
char text[100];
cin.getline(text,sizeof(text));
for(int i = sizeof(text)-1; i >= 0; i--){
if (isalpha(text[i]) || text[i] == ' ' )
decoded.push_back(text[i]);
}
cout << decoded;
return 0;
}

Add #include <string.h> and change
for(int i = sizeof(text)-1; i >= 0; i--){ to
for(int i = strlen(text)-1; i >= 0; i--){
because strlen(text) calculates length upto \n where as sizeof(text) includes \n too.
or as Ruks mentioned in the comment a simple initialization char text[100] {}; works.

Just declare text as an empty array same as char[] text = new char[]{};

Related

I have a char array and I want to insert two more spaces for each space

My logic is as follows :
#include<bits/stdc++.h>
using namespace std;
int main(){
char a[50] = {'h','i',' ','m','e',' ','t','e'};
// k = 4 because i have 2 spaces and for each
// space i have to insert 2 spaces . so total 4
//spaces
int k=4;
for(int i=strlen(a)-1 ; i>0 && k >0 ; i--){
if(a[i] != ' ')
{
a[i+k] = a[i];
a[i] = ' ';
}
else
{
k = k - 2;
}
}
printf("%s" , a);
return 0;
}
I have to character array to solve it. I am able to
do it using string stl
The output i get is
hi---me.
But the answer is
hi---me---te.
Your code is tagged C++. But there is nothing C++ in your code. It is pure C.
And, your are including #include<bits/stdc++.h> and using the std namespace using namespace std;. From now on: Please never ever in your whole life do such things again. Or, stop working with C++.
Additionally never ever use plain C-style array like your char a[50] in C++.
In your code you have some bugs. Most critical is the missing terminating 0 and then calling strlen. Before you use a function, always check somewhere, how this function works. Use meaningful variable names. Write comments. Always check boundaries.
I updated your C-Code:
#include <stdio.h>
int main()
{
// Character String to work on
char charString[50] = "hi me te";
// Check all possible positions in string
for (int index = 0; (index < 49) && (0 != charString[index]); ++index)
{
// If there is a space in the string
if (' ' == charString[index])
{
// Shift all characters one position to the right
for (int shiftPosition = 48; shiftPosition >= index; --shiftPosition)
{
charString[shiftPosition + 1] = charString[shiftPosition];
}
++index;
}
}
// Show result
printf("%s\n", charString);
return 0;
}
And here the C++ solution
#include <iostream>
#include <string>
#include <regex>
int main()
{
// Text to work on
std::string text("hi me te");
// Replace every space with 2 spaces. Print result
std::cout << std::regex_replace(text, std::regex(" "), " ");
return 0;
}

Reformatting an entered string with spaces in it

Currently I am working on a problem to reformat the inputted string into the odd char then even char with no newline. ex. Input: Good Test. Ouput: Go etodTs. For some reason when I run the program it only outputs a "G".
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main (int argc, char ** argv) {
char sWordOdd[100] = {0};
scanf("%s", sWordOdd);
int iNum = strlen(sWordOdd);
for (int i=0; i<=iNum && i%2==0; i++) {
printf("%c",sWordOdd[i]);
}
for (int a=0; a<=iNum && a%2!=0; a++) {
printf("%c",sWordOdd[a]);
}
printf("\n");
return 0;
}
Your i<=iNum && i%2==0 break condition terminates your loop early. To achieve the effect you want, put an if statement inside the loop, like so:
for (int i = 0; i <= iNum; i++){
if(i % 2 == 0)
printf("%c",sWordOdd[i]);
}
As for your second loop, I think you meant a++ instead of a--, because otherwise you'll try to access the array using a negative index. I think you meant for your loop to look like this:
for (int a = 0; a <= iNum; a++){
if(a % 2 != 0)
printf("%c",sWordOdd[a]);
}
Side note: Notice the spacing between the variables and the operators in my code. Using spaces like this makes your code easier to read.
int main()
{
string line;
getline(cin, line);
for (size_t start : {0,1})
for (size_t ii = start; ii < line.size(); ii += 2)
cout << line[ii];
cout << endl;
}
The above code handles arbitrarily long lines, is C++11 rather than C, and works.
As said before the loops terminate if i<=iNum && i%2==0 is true (for the first loop), which is the case for i=0. The second loop terminates with i=1.
Since you want to iterate all characters you have to move the i%2==0 part out of the for-statement:
for (int i=0; i<=iNum; i++) {
if (i%2==0)
{
printf("%c",sWordOdd[i]);
}
}
The second loop needs to be modified in the same way...
To fix this problem you have to use a function that can see stuff after whitespaces. This function is called getline. But with getline, you have to use string, so in this example I used string. I then found the size with the .size() function and then using just one constraint for the for loop instead of two in the question. I also took off the char array and replaced it with string as stated above. Everything else is pretty much the same. Using this answer lets me not having to use cstring and also simplifying my code into a short, easy way that is easy to follow through.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define Set(a, s) memset(a, s, sizeof (a))
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
using namespace std;
int main (int argc, char ** argv)
{
string sWordOdd;
getline(cin, sWordOdd, '\n');
int iNum = (int)sWordOdd.size();
for (int i=0; i<iNum; i+=2){
cout << sWordOdd[i];
}
for (int a=1; a<iNum; a+=2){
cout << sWordOdd[a];
}
printf("\n");
return 0;
}

How to ignore non-letters from std::cin

So, I am trying to read a string from cin, then loop through the string to count which characters in that string are actually letters in the English alphabet. I have wrote a program that works just fine, but I want to know if there is a more efficient way of doing this, without looping through the entire English alphabet.
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(int i = 0; i < my_str.length(); i++){
for(int j = 0; j < alphabet.length(); j++){
if (tolower(my_str.at(i)) == alphabet.at(j)){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
}
cout << countOfLetters;
return 0;
}
EDIT: Here is my new and improved code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(unsigned int i = 0; i < my_str.length(); i++){
if (isalpha(my_str.at(i))){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
cout << countOfLetters;
return 0;
}
enter code here
Use isalpha() to see which characters are letters and exclude them.
So, you could modify your code like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str;
getline(cin, my_str);
int countOfLetters = 0;
for (size_t i = 0; i < my_str.length(); i++) { // int i produced a warning
if (isalpha(my_str.at(i))) { // if current character is letter
++countOfLetters; // increase counter by one
}
}
cout << countOfLetters;
return 0;
}
You could perhaps use isalpha:
for(int i = 0; i < my_str.length(); i++)
if (isalpha(my_str.at(i))
countOfLetters++;
You can use the std::count_if() algorithm along with the iterator interface to count characters for which some predicate returns true. The predicate can use std::isalpha() to check for alphabetical characters. For example:
auto count = std::count_if(std::begin(str), std::end(str),
[&] (unsigned char c) { return std::isalpha(c); });
You could also check if the int cast is between 65-90 or 97-122
at example
(int)'a'
Should give 97
This will be the most performant method without any doubt.
Its better than using isalpha().
Check http://www.asciitable.com/ for ASCI Numbers
isalpha works well for this particular problem, but there's a more general solution if the list of characters to accept wasn't so simple. For example if you wanted to add some punctuation.
std::set<char> good_chars;
good_chars.insert('a'); good_chars.insert('A');
good_chars.insert('b'); good_chars.insert('B');
// ...
good_chars.insert('z'); good_chars.insert('Z');
good_chars.insert('_');
// the above could be simplified by looping through a string of course
for(int i = 0; i < my_str.length(); i++){
countOfLetters += good_chars.count(my_str[i]);
}

String output gives weird letters

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
string s = "Too many tags";
for(int i = 0; i < s.size(); i++){
if(!(isspace(s[i]))){
s[i] = '#' + s[i];
}
}
cout << s << endl;
return 0;
}
I'm trying to make a program which adds # tag before each letter in the string, but on output I get weird letters.. where is my mistake?
s[i] = '#' + s[i];
modifies the value of an existing character. If you want to add new characters into your string, you should use insert:
s.insert(i, "#");
As Mark Ransom points out, you also need to move one further char through your string to avoid constantly adding "#" before the same letter. You could do this using
s.insert(i++, "#");
Note that you could always take VladimirM's advice and make slightly larger changes to something like
int i=0;
while (i<s.size()) {
if (!isspace(s[i])) {
s.insert(i++, "#");
}
i++;
}
This line:
s[i] = '#' + s[i];
isn't doing what you think it is. s[i] is a char, # is also a char. Adding these together doesn't give you the concatenation of the two characters, it gives you the addition of the integer code of the characters (so 35 for # and the ASCII code for whatever s[i] happens to be).
I add more: I think the simpler way is to use temporary variable otherwise your loop with 'insert' will go to endless loop and will hang:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
string s = "Too many tags";
string res = "";
for(int i = 0; i < s.size(); i++){
if(!(isspace(s[i]))){
res += "#";
}
res += s[i];
}
cout << res << endl;
return 0;
}

My Program Only Processes One Line From The Input

I'm doing a Caesar block cypher. The general steps to a solution are:
Read your message into a large buffer or a string object.
Either remove the spaces and punctuation or not (it's harder for the
Enemy to read if you do).
Then count the chars in the message.
Pick the first perfect square greater than the message length,
allocate an array of char that size.
Read the message into a square array of that size from left to right,
top to bottom.
Write the message out top to bottom, left to right, and you've
encyphered it.
My Code:
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <ctype.h>
#include <cmath>
#include <functional>
#include <numeric>
#include <algorithm>
#include <locale>
using namespace std;
int main(int argc, char *argv[])
{
int length = 0;
cout << "Enter a string: ";
string buffer;
char buff[1024];
while (getline(cin, buffer))
{
buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
break;
}
length = buffer.length();
int squareNum = ceil(sqrt(length));
strcpy(buff, buffer.c_str());
char** block = new char*[squareNum];
for(int i = 0; i < squareNum; ++i)
block[i] = new char[squareNum];
int count = 0 ;
for (int i = 0 ; i < squareNum ; i++)
{
for (int j = 0 ; j < squareNum ; j++)
{
block[i][j] = buff[count++];
}
}
for (int i = 0 ; i < squareNum ; i++)
{
for (int j = 0 ; j < squareNum ; j++)
{
cout.put(block[j][i]) ;
}
}
return 0;
}
For the most part, it works. The problem I get is when there's more than one line of input.
Ex. 1
this is sample text suitable for a simulation of a diplomatic mission or a spy's instructions
Ex. 2
this is sample text suitable
for a simulation of a diplomatic
mission or a spy's instructions
Example 1 works and example 2 does not because there are multiple lines. I have a feeling it has to do with the while(getLine) function but I don't know exactly what to change.
This "break" inside the "while" loop - it breaks the loop after the first "getline" call. That's why you get only one line.
May be you should consider removing break after erase.
What you do in here:
while (getline(cin, buffer))
{
buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
break;
}
is saving new line to buffer every time you use getline. I mean, each time there is getline() evoked your buffer is being replaced, not appended.
Try this:
string buffer = "";
string buff2;
// You need to provide some way to let the user stop the input
// e.g. ask him to declare number of lines, or what I recommend
// check for an empty line given, which is implemented below:
while (getline(cin, buff2))
{
// now pressing [enter] after the last input line stops the loop
if (buff2.empty())
break;
buff2.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
buffer += buff2;
}