`
The asked program was to input two string and print their respective size as first line in output while the second line contains the concatenation of two string and the third line of output contains the original string after the first character of both the string have been swapped..below is my code..everything is working except while printing the second string it is printing unnecessary characters because of which entire second string is not being printed
PS: i'm new to c++
int main()
{
string a,b,c;
cin>>a>>b;
int j=a.size();
int k=b.size();
char s[j],p[k];
cout<<a.size()<<" "<<b.size()<<endl;
c=a+b;
cout<<c<<endl;
for(int i=0;i<a.size();i++)
{
s[i]=a[i];
}
for(int i=0;i<b.size();i++)
{
p[i]=b[i];
}
char t;
t=s[0];
s[0]=p[0];
p[0]=t;
cout<<s<<" ";
cout<<p;
return 0;
}`
input:
dlxecxsye
bfjoosgukxgywz
output:
9 14
dlxecxsyebfjoosgukxgywz
blxecxsye
# dfjoosgukxgywz
desired output:
9 14
dlxecxsyebfjoosgukxgywz
blxecxsye dfjoosgukxgywz
Your string p is of size k, which is size of input b (14).
In your for cycle you iterate from 0 to size of input a (9), which in your case is smaller than size of input b.
When you output content of p at the end of your code, chars at indexes from 9 to 13 are not set and you print something undesired from that place in a memory.
I don't understand the need for the character arrays.
// Swapping first characters
char temp = a[0];
b[0] = a[0];
a[0] = temp;
Please use the debugger and verify that your character arrays are terminated by a nul character.
See also: std::string::c_str() and strncpy.
Related
I wrote a function in C++ which removes two characters from a char array. I think when I assign str[o+2] to str[o], the str[o+2] shoud not be changed. But when I use cout to print it, I see that str[o+2] is altered with null.
#include<iostream>
#include<string.h>
using namespace std;
void shiftLeft(char*,int, int);
int main(){
char str[100];
cout<<"enter the string: ";
cin>>str;
cout<<"removes the letter with index i and i+1\nenter i:";
int i;
cin>>i;
int n=strlen(str);
shiftLeft(str,i,n);
cout<<str;
return 0;
}
void shiftLeft(char*str,int i, int n){
for(int o=i-1; o<n; o++){
str[o]=str[o+2];
}
}
For example with input "abcdef" and i=3, I expect output "abefef" but I get "abef". where are the last "ef"? Why are they ignored?
abcdef0???... <- the contents of array (0 means NUL, ? means indeterminate)
ef0? <- what is written to the position (shifted 2 characters)
Assigning str[o+2] to str[o] itself won't changestr[o+2],
but later o will come to o+2 thanks to the for statement and then assigning str[o+2] to str[o] means assigning str[o+4] to str[o+2] with original o value.
Then, terminating null character is written and the string ends.
I have trouble understanding the following code,
static char s[N][N];
int i = 0;
while( gets(s[i]) )
{ some loop, where i gets incremented }
considering the array is of N dimensions, then what happens when
gets(s)
is called? How can it store the entire string in the s[i] element? It feels like s[i] should be equal to the first char of the input, and not the entire string. And what happens when it loops with more input? The point is to have it stored as
[char, char, char, char]
[char, char, char, char, char]
[char, char, char, char, char, char]
... and so forth
which it seems like the code is currently doing. But I don't understand how.
EDIT #1
A lot of people suggested against using gets(), but why would gets() not be appropriate when there can be no illegal input and I want to store the characters as elements in an array and not as a string?
The s[i] element is an array of characters since s is an array of arrays. An array of characters can be used to store a string by using a zero character (called a "nul") to mark the end.
The code above is storing the string but with a numbered index.
But storing that number index in the first dimension of the array.
Think of it in this way, I want to store 10 strings of max size of 256 char:
int main()
{
char s[10][256];
for (int i = 0; i < 10; i++ ) {
gets(s[i]);
}
for (int i = 0; i < 10; i++ ) {
cout << s[i] << endl;
}
}
cout << s[1][2] << endl;
Note: for the last line in the code above it would output the second entry (we ordered everything from 0-9) and third character of the string at that entry.
Thus, if my entry was test2 then the output would be 's'.
Note: It would be incorrect to call gets(s) as it will not compile and is not the intention of the code.
gets() call has some features that can land you into a buffer overflow problem if the input is not monitored.
Example:
int multi_array[2][2] = {{2,3,4},
{7,8,9},
{1,5,0}};
Array[n][m]
Gets
First position Array[0][0]
Second position Array[0][1]
Position 0,1 is 3
Position 1,2 is 9
Position 2,2, is 0
Why does c-string length matter when using for loops? Is there an issue with the termination character '\0'?
The following code sends the for loop into a crazy loop that crashes the compiler:
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
char c[] = "charac";
int i;
for (i=0; i < 8 ; i++)
{
cout << c[i] << endl;
}
return 0;
}
By adding a 't' to my c-string, the code runs perfectly fine:
char c[] = "charact";
int i;
for (i=0; i < 8 ; i++)
{
cout << c[i] << endl;
}
In your first version, there is no character c[7]. You have 7 characters in the array, 6 characters of string and 1 null terminator:
Array: c h a r a c \0
Indices: 0 1 2 3 4 5 6
Attempting to access anything beyond that is undefined behavior.
In your second version, assuming the code you're running has the t you forgot to put in the posted version, the array has 8 characters, and the loop stays within the bounds of the array.
You have a string of length 7 (6 + null terminator), and are attempting to access an 8th element. This will result in undefined behavior.
I think that you are stepping past the end of the end of your character array. By adding the extra character, your string is now 7 characters long so the i<8 test works.
You are index past the end of the array. C starts indexing at zero so the last index of a six character string is five. If you include the null terminator then you have six but you are accessing the seventh array position.
c[7] doesn't exist for "charac" as c[6] is the null terminating character. But when you change it to "charact" then c[7] becomes the null terminating character so it runs fine.
I have a string that contains what ever the user has input
string userstr = "";
cout << "Please enter a string ";
getline (cin, userstr);
The string is then stored in userstr, I then want the string to be stored in a integer array where each character is a different element in the array. I have created a dynamic array as the following:
int* myarray = new int[sizeof(userstr)];
However how do I then get my string into that array?
You can access each element in your string using the [] operator, which will return a reference to a char. You can then deduct the int value for char '0' and you will get the correct int representation.
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i] - '0';
}
int* myarray = new int[ userstr.size() ];
std::copy( usestr.begin(), userstr.end(), myarray );
The terminating zero was not appended to the array. If you need it you should allocate the array having one more element and place the terminating zero yourself.
You can just simply use isstringstream to convert the string to int as follows
istringstream istringName(intString);
istringName >> real_int_val;
now it has magically become a int containing all numbers from string
However I do not see why you would not cin it as a int in the first place??
Here is one way to do it
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i];
}
int main()
{
cout<<"Enter a word"<<endl;
char word1[]={0}; //first char array initialization
cin>>word1;
cout<<"Enter another word"<<endl;
char word2[]={0}; //second char array initialization
cin>>word2;
char word3[]={0};
char word4[]={0};
int i=0;
while (word1[i]!='\0') //this converts both words to lower case by usinction tolower
{
word3[i]=char(tolower(word1[i])); //word3 and word4 stores the new arrays
word4[i]=char(tolower(word2[i]));
i++;
}
int output; //output stores the value of 0,1 or -1
output=compareString(word3,word4);
if (output==0)
{
cout<<"The two words are the same."<<endl; //if arrays are same
}
if (output==1)
{
cout<<"the 1st character of 1st word has a larger value than of 2nd word."<<endl;
}
if (output==-1)
{
cout<<"the 1st character of 2nd word has a larger value than of 1st word."<<endl;
}
return 0;
}
int compareString(char string1,char string2)
{
int size1=0; //initialize size of string1
int j=0; //string1 position initialize
while (string1[j]!='\0') //loop to determine size of string1
{
size1+=1;
j+=1;
}
int a=0; //initialize size of string2
int size2=0; //string2 position
while (string2[a]!='\0') //loop determines size of string2
{
size2+=1;
a+=1;
}
int i=0;
int k=0;
for (i=0;i<size1;i++) //loop to compare the two strings
{
if (string1[i]!=string2[i])
{
if (string1[i]>string2[i]) //comparing 1st character of string1 & string2
{
return 1;
}
else //if string2's first character is greater in value
{
return -1;
}
}
else
{
k++; //incrementing k when character of string1 matches string2 character
}
}
if (k==size1) //to cjheck if all characters of both strings are same
{
if (k==size2)
{
return 0;
}
}
}
This is a function which compares two char arrays and returns 0 if characters correspond to each other,returns 1 if first character of string1 is greater than first character of string2 in value and returns -1 if first character of string1 is less than first character of string2.The problem is that when i run it,even when the two words are different,the output is always 0 and the text "The words are the same" appears.
Am i initializing the two arrays correctly in my main program?or is there some other problem?
This declaration
char word1[]={0};
declares an array of size 1, meaning when you do your input it will overwrite the stack. The same for all other arrays.
When dealing with string in C++ it is highly recommended to use std::string!
char word1[]={0};
This line creates an array word1 that has exactly one element, set to 0. When using this array to hold a string, you cannot hold anything in this except the empty string. You are causing a buffer overflow here, because you read a non-empty string into this array, which will then write into other parts of memory not allocated to this array. This is very bad.
Consider using std::string to hold strings instead. It will automatically resize its allocation as necessary.