#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
char zahl[255];
cin>>zahl;
for(int i=255; i>=0; i--)
if(zahl[i] != 0)
cout<<zahl[i];
cout<<endl;
return 0;
}
When I enter some words the input gets reversed but before and after that there are undefined expressions. Can someone explain the reason for this?
As far as I understood, the char array is filled with the inserted expression (from [0] on), the rest is filled with '\0's. By the if condition I skip the '\0's. Where do the undefined expressions come from?
ty
greets CS
Initially, the array is uninitialised and contains garbage. cin writes the input followed by a single zero to terminate; the rest of the array still contains garbage, which your loop outputs before the input.
You could specify that the array be zero-initialised:
char zahl[255] = {};
Or you could measure the string length, and start from there:
for (int i=std::strlen(zahl)-1; i >= 0; i--)
Or, better still, use the standard library to fix the potential buffer overrun:
std::string zahl;
std::cin >> zahl;
std::copy(zahl.rbegin(), zahl.rend(), std::ostream_iterator<char>(std::cout));
Your for loop will run 256 times, assuming that the word entered is 255 characters long. However, user input will vary in length, so instead calculate the length and use it in the for loop.
int len = strlen(zahl);
The code will now be:
#include <iostream>
#include<string.h>
using std::cout;
using std::cin;
using std::endl;
int main(){
char zahl[255];
cin>>zahl;
int len = strlen(zahl);
for(int i=len-1; i>=0; i--)
if(zahl[i] != 0)
cout<<zahl[i];
cout<<endl;
return 0;
}
Related
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[]{};
#include <iostream>
using namespace std;
int main(){
string s,str;
cin>>s;
int a[26]={0};
for(int i=0;i<26;i++){
int x=(int)s[i]-97;
if(a[x]==0){
a[x]++;
str+=s[i];
}
}
cout<<str<<endl;
return 0;
}
Input : geeksforgeeks
Ouput:geksfor
�
This is where i am getting some extra characters as ouput why i am getting like that?
Can anyone help me ?
Thanks in advance.
Your loop runs with i in range [0, 26), where i is indexing s, regardless of the length of s (and in this case, s is much shorter than 26 character long). Eventually, you index outside the bounds of s (invoking undefined behavior) and start processing gibberish, and your code starts pushing unique gibberish onto your result string. If you can assume your inputs are always lowercase ASCII, you could iterate with i in range [0, s.size()) (or use C++11 for-each style looping without indexing at all), but short-circuit out if str reaches a length of 26 (because all 26 unique characters have been seen).
One approach:
int main(){
string s,str;
cin>>s;
int a[26]={0};
for(auto c : s){
int x = c-97;
if (a[x] == 0) {
a[x]++;
str += c;
if (str.size() == 26) break;
}
}
cout<<str<<endl;
return 0;
}
I think you have consider the input string in lower case letters.
But one mistake you have done in the code is that you are iterating the for loop for only 26 times.
But lets consider the string such that the letters are repeated after 26th character. There only your code fails. So, you just have to iterate through the whole string.
The correct code is:
#include<iostream>
using namespace std;
int main()
{
string s,str;
cin>>s;
int a[26]={0};
for(int i=0;i<s.size();i++)
{
int x=(int)s[i]-97;
if(a[x]==0)
{
a[x]++;
str+=s[i];
}
}
cout<<str;
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code. What i wanted to do is to replace every letter from every char with indicated number. Like for A is 10, and so on until J, 19. My code works well if i have only one letter in my char array, but if i have more after another it copies useless things. I think that something is wrong with strncat.
#include<conio.h>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char litera[11]={"ABCDEFGHIJ"};
char cifra[11]={"0123456789"};
char rezultat[256]={0};
int n;cin>>n;cin.get();
for(int i=0;i<n;i++)
{
char x[256];
cin.get(x,256);cin.get();
int k=strlen(x);
for(int j=0;j<k;j++)
{
int p = strchr(litera,x[j])-litera;
if(p>=0 )
{
strncat(rezultat, x,j);
// my p is the indicator for letter and number
strcat(rezultat,"1");
// I'm copying an 1 there because i have numbers
// between 10-19 and in my int array i have only
// the second cipher
strcpy(x,x+j);
rezultat[strlen(rezultat)]=cifra[p];
}
}
cout<<rezultat<<endl;
memset(rezultat,0,sizeof(rezultat));
}
getch();
return 0;
}
Input: 07B, 1AA, C8A
Output: 0711, 11010, 12810
My output:
0711
110AA1
12C810
If you guys can tell me where the problem is, you'll help me a lot, every suggestion is well received, even if is not about this problem. Thanks!
If it is allowed to use vector and string then you can try the following (I tested it and it works.) The input here should be line by line(each line is a new string to be converted) but of course you may modify this part based on your input format:
Include those:
#include <vector>
#include <iostream>
#include <string>
//#include <conio.h>
//#include <cstring>
//using namespace std;
int main()
{
int n;
std::cin >> n;
while (n--)
{
string input;
std::cin >> input;
vector<char> resultat;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J') // it is a letter between A and J
{
int number = input.at(i) - 'A' + 10;
char ones = (char)(((int)'0') + (number % 10));
char tens = (char)(((int)'0') + (number / 10));
resultat.push_back(tens);
resultat.push_back(ones);
}
else
resultat.push_back(input.at(i));
}
for (int i = 0; i < resultat.size(); i++)
{
std::cout << resultat[i];
}
std::cout << endl;
}
}
if string is not allowed just use your character array. There seems to be nothing wrong in your input format.
If vector is not allowed either, then you may create a char pointer the initialize it based on the final size.
For example:
int newSize=0;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J')
newSize+=2;
else
newSize++;
}
char* resultat = new char[newSize];
...
Then just fill the resultat.
Hope that helps!
Do you have to do it with your multiple arrays? You could perform a switch-case for only specified inputs. Since you are replacing letters A-J with numbers 10-19, you can easily implement this in switch case. You can also check for incorrect input as well.
If you have to use arrays, first question is why is you numerical array the single digits? Is this is constraint? Cant you use :
char cifra[11]={"10","11","12","13","14","15","16","17","18","19"};
for the array instead, that way you can refer to the array index and replace it using the index? This way, you can compliment the arrays by just using index referencing to replace the output based on the index, such as A is index 1 for alphabetical array which refers to index 1 of the numerical array which is "10" so you just print the array index value to a variable and output 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;
}
I'm doing some basic input parsing in c/c++.
format: number of values, followed by space separated values:
3
5 2 4
The problem here is the lack of a space after the first line. This causes cin and scanf to read 35 into the first variable, instead of 3.
int num;
scanf("%d", &num);
int array[num];
for (int i = 1; i <= num; i++) {
scanf("%d", &array[i]);
}
How do I get cin, or scanf, to stop parsing at a newline?
Edit:
Is it bad not to init variables even if they are written to later, before being read? (int num)
It works if I type the input in, but not if I paste it. Any clue?
std::cin interprets newline characters as spaces so there is the possibility the file you are working with contains something other than a newline. You are also using a non-standard extension to declare the array. This is not portable and not guaranteed to be supported by all compilers. I suggest you switch to using std::vector instead.
Your for loop is also incorrect. Array's used zero based indexing to access their elements. Because of this you end up accessing the array out of bounds which is undefined behavior. This means your program might crash, it may overwrite other variables or you might not notice any symptoms at all. This may also cause the symptom you are experiencing if it overwrites other variables.
The example below uses C++ input streams instead of scanf to provide better error checking.
#include <istream>
#include <vector>
std::vector<int> load(std::istream& in)
{
std::size_t count;
std::vector<int> data;
// If the user does not enter a number "in >> count" will fail.
if (in >> count)
{
int value;
while (count-- && in >> value)
data.push_back(value);
}
return data;
}
#include <iostream>
int main()
{
auto data = load(std::cin);
for (auto i : data)
std::cout << i << std::endl;
}
You can test this without reading from a file by using std::stringstream as the input.
#include <iostream>
#include <sstream>
int main()
{
std::stringstream text("3\n5 2 4");
auto data = load(text);
for (auto i : data)
std::cout << i << std::endl;
}
Within the for loop you started the array at position 1 and not 0. Which would cause going out of bounds, as you wanted to write to element 2 of the array. If you allocate an array of 2 elements the valid elements are going to be 0 and 1. This code works:
int num;
scanf("%d", &num);
int array[num];
for (int i = 0; i < num; i++)
{
scanf( "%d", &array[i] );
}
Start array from 0 as array indexes start from 0 - like:
for (int i = 0; i < num; i++)
You are starting first element from 1 that makes it undefined. Moreover, you should make dynamic array.
I liked Lidong Guo's code, and have modified it to run with Microsoft's C Compiler.
The only change was to move all of the data definitions ahead of any executable code, plus I added a space between the printed numbers.
#include <stdio.h>
#include <stdlib.h>
main()
{
int num;
int *array; //[num];
int i;
scanf("%d\n", &num);//here deal with the newlinw
array= malloc(sizeof(int) *num);//[num];
for (i = 0; i < num; i++)
{//the loop .start 0 end num -1
scanf("%d", &array[i]);
}
for (i = 0; i < num; i++)
{
printf("%d ", array[i]);
}
free(array);
}
[Edit: The Answere is specific to C++, as the Question also have a C++ tag]
Well first thing first.
You array defination is wrong .
int array[num]; // Super wrong way
You are not supposed to pass a variable as index while defining an array, its not allowed. Else, it will cause "nasal demon".
int * array = new int[num] //correct way
The code might be working correctly now but the array definition given by you lies under the category of UB.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
scanf("%d", &num);
int *array= malloc(sizeof(int) *num); // num is known at runtime
int i;
for (i = 0; i < num; i++) { //starts at 0, ends at num - 1
scanf("%d", &array[i]);
}
for (i = 0;i< num; i++) {
printf("%d", array[i]);
}
free(array);
}
Change the
scanf
statement to
scanf("%d", &array[i]);
Also array indexing starts from 0 and ends at num-1
Start your loop from 0 and end it at num-1,i.e
for (int i = 0; i < num - 1; i++)
scanf("%d", &array[i]);
And the reason for pasted input does not work is that it doesn't contain newline between two lines