cstring problom

Im having a bit of trouble here. The program below allows the user to enter a word, if that word ends with the letter "y" then it changes it to "ies". But instead it is changing the last letter of every word to ies.

How would I go about fixing this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdlib>
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char str1[30];
    char str2[30];
    
    cout<<"Enter a Word"<<endl;
    cin.getline (str1, 30+1);
    int lenght = strlen(str1);
    char lastChar = str1[lenght-1];
    if (lastChar ='y'){
                 strncpy (str2,str1,(lenght-1));
                 str2[lenght-1]= '\0';
                 strcat (str2, "ies");
                 cout<<str2<<endl;
                 }
                 
                     
    system("PAUSE");
    return EXIT_SUCCESS;
                 }  
if (lastChar ='y'){

= is assignment
== is comparison
Thanks, should of figured that myself.
Ok another problem has happened. The program below is meant to delete the 1st character if it is a space but instead of just deleting the 1st character it deletes the entire string.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    char str1[]= "   TEST";
    cout<<str1<<endl;
    int len=strlen(str1);
   while (str1[0]==' '){
         cout<<"Deleting 1st char"<<endl;
 str1[0]= '\0';
}
   cout<<str1<<endl;
   
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
You just added a terminator in the first spot. That kills the string. Instead try manually shifting everything over:

1
2
3
while (str1[0]==' ')
  for (int i = 0; i < strlen(srt1)-1; i++)
    str1[i] = str1[i+1];


That did the trick, cheers
Topic archived. No new replies allowed.