I am a beginner to C programming and am trying to "Split a string into separate words and write the string in reverse".
Sample Input : Hello World it's FUBAR
Sample Output: FUBAR it's World Hello
I have tried it with this code so far on CodeBlocks 13.12(Windows 8.1/AMD A8) :
#include<stdio.h>
#include<string.h>
char str[100];
char word[100][100];
int main(){
fgets(str,100,stdin);
int i=0,j=0,k=0;
for(i=0;i<100;i++){
while(str[i]!=' ' || str[i]!='\0')
{
word[j][k]=str[i];
i++;
j++;
}
if(str[i]==' '){
k++;
}
}
while(k>0){
for(j=0;j<100;j++){
printf("%s",word[j]);
}
printf(" ");
k--;
}
return 0;
}
The code compiles with 0 errors, 0 warnings.
But when I build and run the code, it crashes with error message -1073741510.
I have been trying for many hours now but have not been able to figure out where exactly the code is breaking.Please help me with this one.
Please try this code.
1) Eliminated extra looping.
2) Swapped j and k variables . Each row would constitute a new word.
3) word[0][1..100] would the first word and word[1][1..100] would be second word.
int main(){
fgets(str,100,stdin);
printf("str is [%s]\n",str);
int i=0,j=0,k=0;
for(i=0;i<100;i++){
printf("char is [%c]\n",str[i]);
if( str[i]!=' ' && str[i]!='\0' )
{
word[j][k]=str[i];
k++;
}else if(isspace(str[i]) || str[i] == ' '){
printf("space found\n");
j++;
}
}
printf("value of j [%d]\n",j);
while(j>=0){
for(k=0;k<100;k++){
printf("%c",word[j][k]);
}
printf(" ");
j--;
}
return 0;
}
Your for loop looks wrong, it should be
for(i=0;i<100;i++)
{
while(str[i]!=' ' || str[i]!='\0')
{
word[j][k]=str[i];
i++;
k++;
}
if(str[i]==' ')
{
j++;
}
}
Notice the k and j increment swap.
In the first while increase k instead of j.
In if(str[i]==' ') set the null termination for word[j][k] and then increase j instead of k.
Below is a Corrected Code. Note the Output doesn't come exactly in one single line. For example the output will always come like this,
EDIT: Thanks to a point reminded by Rad Lexus in the comments. I was able to mitigate the problem a bit
Changes made in Code:
Changed the following code line to
for(i=0;i<strlen(str);i++)
This,
for(i=0;i<strlen(str)-1;i++)
Although, the problem of outputting all the words in the same line is solved,
but there is another problem. Now there is no space between the first and the Second word.
So, the new problem is,
Example 1:
Input: Welcome to Bravo
Output: Bravoto Welcome
Example 2:
Input: Hello World it's FUBAR
Output: FUBARit's World Hello
A temporary solution to the above problem is to change this code
for(m=j;m>=0;m--){
printf("%s",word[m]);
}
To this code,
for(m=j;m>=0;m--){
if(m == j){
printf("%s ",word[m]);
}
else{
printf("%s",word[m]);
}
}
(I guess this problem occurs due to mapping from a 1D Array to a 2D Array and there is probably some padding involved.) -> Edit:This is not due to padding but, "I guess this problem occurs due to.." – no, it occurs due to fgets which also stores the terminating newline code-Rad Lexus.
Anyways, here is the code,
#include<stdio.h>
#include<string.h>
char str[100];
char word[100][100];
int main(){
int i=0,j=0,k=0;
int m=0;
fgets(str,100,stdin);
for(i=0;i<strlen(str)-1;i++){
if(str[i]!=' '){
word[j][k]=str[i];
//printf("%c",word[j][k]);
k++;
}
if(str[i] == ' ' || str[i] == '\0'){
word[j][k]=' ';
k=0;
j++;
}
}
for(m=j;m>=0;m--){
printf("%s",word[m]);/*----->TEMPORARY SOLUTION
for(m=j;m>=0;m--){
if(m == j){
printf("%s ",word[m]);
}
else{
printf("%s",word[m]);
}
}*/
}
return 0;
}
Related
when i run this code in the terminal i get a blank line that just wait for nothing
when i move the "i++;" under the "while(str[i]!='\0')" it works but thats not what i wanted , any help?
int main(){
printf("hello kiddo");
char str[20]="hel a awdaw dwa";
int i=0;
char *cleanstring;
while(str[i]!='\0'){
if(str[i]==' '){
continue;
}
else{
printf("%c",str[i]);
}
i++;
}
return 0;
}
i dont know what wrong with this code
In addition to Johnny Mopp's comment, notice the difference when adding the \n to your printf your program needs to flush the character and will not until the end of line, which as he says never happens since the loop gets stuck.
int main() {
printf("hello kiddo");
char str[20] = "hel a awdaw dwa";
int i = 0;
char * cleanstring;
while (str[i] != '\0') {
if (str[i] != ' ') {
printf("%c\n", str[i]);
}
i++;
}
return 0;
}
i solved this problem editing the "if condition" like that
while(str[i]!='\0'){
//if(str[i]==' '){
// continue;
//}
//else{
// printf("%c",str[i]);
//}
//i++;
if(str[i]!=' '){
strncat(cleanstring,&str[i],1);
}
i++;
}
the code was long for no reason and its better right now but , still wanna know why it didn't work in the first time.
I've tried to make a code that encrypts a message in ROT13, i'll leave here the whole code.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<ctype.h>
#include<locale.h>
#include<string.h>
#define MAX 500
int main(){
int i,diff[i];
char string[MAX];
printf("\x1b[34mHello friend,this is a simple ROT13 decryption algorhytm brought to you by #NikoScaccia\x1b[0m\n");
printf("\x1b[31mPlease Enjoy!!!\x1b[0m\n");
printf("\n");
printf(">>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<\n");
printf("\n");
printf("Insert a phrase: \n");
printf("\x1b[0,35mMAX LEN: %d\x1b[0m\n",MAX);
scanf("%99[^\n]",string);
for(i=0;i<'\0';i++){
if(string[i]<='a' && string[i]<='z' || string[i]>='A' && string[i]<='Z'||!isspace(string[i])){
string[i]=tolower(string[i]);
}
else {
printf("Invalid Input!\n");
exit(EXIT_FAILURE);
}
}
for(i=0;i<strlen(string);i++){
if(string[i]!=' '){
if((int)string[i]+13<=122){
string[i]=(int)string[i]+13;
}
else {
if(string[i]!='n'){
diff[i]=122-(int)string[i];
string[i]=(int)string[i]+diff[i];
string[i]= (int)string[i]-26+13-diff[i];
}
}
}
}
printf("Encrypting...\n");
printf("Encrypted message: %s\n",string);
return 0;
}
the code compiles correctly but it has two main problems,it seems to translate correctly every letter in the alphabet except for the letter 'n' which for some reason translates to '{',
also if I try to feed the program something like "hello man" it executes correctly(except obviously for the letter n),while if for example I try "hello friend" i get a segmentation fault error.
Can someone help me with this?
Thank you in advance.
At least these problems:
Uninitialized i
i is not known when diff[i] is defined. Array size unknown, potentially invalid.
int i,diff[i]; // Bad
Do not define diff[] until after i is assigned.
Define diff[] after the for(i=0; string[i]; i++){...} loop below.
Wrong compare
Loop never iterates.
// for(i=0;i<'\0';i++){
for(i=0; string[i]; i++){
Wrong compare
<= vs. >=
//string[i]<='a' && string[i]<='z'
string[i]>='a' && string[i]<='z'
Unneeded compare
Why test string[i] is not a space?
// if(... || !isspace(string[i])) {
if(...){
Simplification
Tests not needed.
// for(i=0;i<'\0';i++){
// if(string[i]<='a' && string[i]<='z' || string[i]>='A' && string[i]<='Z'||!isspace(string[i])){
// string[i]=tolower(string[i]);
//}
for(i=0; string[i]; i++){
string[i]=tolower((unsigned char) string[i]);
}
int diff[i]; // Now define `diff[]`
#include<stdio.h>
int main() {
char text[1000];
int ch;
int index = 0;
while ((ch = getchar()) != EOF) {
text[index] = ch;
index++;
}
text[index] = '\0';
int i =0;
int num_Count=0;
int lower_Count=0;
int upper_Count =0;
while(i < index) {
if((text[i]>='0') && (text[i]<='9')){
num_Count ++;
i++;
}
else if((text[i]>='A') && (text[i]<='Z')){
upper_Count++;
i++;
}
else if((text[i]>='a') && (text[i] <='z')){
lower_Count++;
i++;
}
else
i++;
}
printf("%d %d %d", num_Count, lower_Count, upper_Count);
return 0;
}
It is a program that outputs the number of lower case, upper case, and number when the sentence is inputted.
For example,
Hi
Name
100
Would output 3 4 2
I keep seeing a runtime error.
The (while) part seems to be wrong.. I do not know what's wrong.
I ran your code in my system and checked for the input: Hi Name 100. The output I got is 3 4 2 which is the expected output. I feel the only place where the code can run in an infinite loop is while reading the inputs. Try to use ctrl+ d for EOF or ctrl+ z for windows.
Rest every thing is fine.
EOF means End Of File. It is used when you read data from a file. I suggest put a character like newline ('\n').
I am creating a program where I insert a number of sentences and the program outputs them in order. I have finished the program, but when I run it it seems like the characters I input into the array aren't displayed or stored correctly, getting as a result random letters instead of the full sentence. Here is the code of the program:
char ch;
int i,j,k;
int nothing = 0;
int count = 1;
char lines[5][256];
int length[256];
int main() {
printf("Please insert up to a max of 5 lines of text (Press enter to go to next line and twice enter to stop the program):\n");
i = 0;
while (i<5){
j = 0;
ch = getche();
if (ch == '\r'){
if(i!= 0){
break;
}
printf("You have not inserted anything, please insert a line:");
i=-1;
}
if(ch != '\r'){
lines[i][j]=ch;
while (ch!='\r'){
ch = getche();
lines[i][j] = ch;
j++;
}
}
printf("\n");
i++;
}
for (k=i ; k > 0; k--){
printf("\tphrase %i :", count);
for ( j =0 ; j <= length[k]; j++){
printf("%c",lines[j][k]);
}
count++;
printf("\n");
}
return 0;
}
How can I get the characters to be stored and displayed correctly? Any help is appreciated, thank you!!
There are numerous problems with your code. I'll try and summarise here, and give you improved code.
Fist, some changes that I made to get this to compile on my system:
Changed getche() to getchar() (getche() does not appear to be available on Ubuntu).
I took out the section about re-entering a string, and just focused on the rest (since the logic there was slightly broken, and not relevant to your question). It will still check for at least one line though, before it will continue.
I had to change the check for \r to \n.
I changed your length array to size 5, since you'll only have the lengths of maximum 5 strings (not 256).
Some problems in your code:
You never updated the length[] array in the main while loop, so the program never knew how many characters to print.
Arrays are zero indexed, so your final printing loops would have skipped characters. I changed the for parameters to start at zero, and work up to k < i, since you update i after your last character in the previous loop. The same with j.
Your reference to the array in the printing loop was the wrong way around (so you would've printed from random areas in memory). Changed lines[j][k] to lines[k][j].
No need for a separate count variable - just use k. Removed count.
The nothing variable does not get used - removed it.
#include <stdlib.h>
#include <stdio.h>
char ch;
int i,j,k;
char lines[5][256];
int length[5];
int main()
{
printf("Please insert up to a max of 5 lines of text (Press enter to go to the next line and twice enter to stop the program):\n");
i = 0;
while (i<5)
{
j = 0;
ch = getchar();
if ((ch == '\n') && (j == 0) && (i > 0))
{
break;
}
if (ch != '\n')
{
while (ch != '\n')
{
lines[i][j] = ch;
j++;
ch = getchar();
}
}
length[i] = j;
printf("\n");
i++;
}
for (k = 0; k < i; k++)
{
printf("\tPhrase %i : ", k);
for (j = 0; j < length[k]; j++)
{
printf("%c", lines[k][j]);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[1000];
int i, letter, space = 0;
char ch = str1[i];
printf("Enter a sentence: ");
scanf("%[^\n]s", str1);
printf("you enter %s\n", str1);
while (i != strlen(str1)) {
if (ch != ' ') {
letter++;
} else if (ch = ' ') {
space++;
}
i++;
}
printf("%d %d", letter, space);
}
My while loop isn't working and I can't seem to locate the problem. I am using the terminal in ubuntu and after printing the user string, I get a blank line. I have to use Ctrl-Z to stop the script.
Mistakes I see: using uninitialised variables - local variables do not get initialised automatically.
Another is you do not read a character from the string within the loop.
The third is the unecessary and syntactically incorrect if (ch=' ') which should have been if (ch==' ')
#include<stdio.h>
#include<string.h>
int main(void){
char str1[1000];
int i = 0, letter = 0, space = 0; // initialise all to 0;
printf("Enter a sentence: ");
scanf("%[^\n]s",str1);
printf("you enter %s\n",str1);
while (i!=strlen(str1)){
char ch = str1[i]; // move this inside the loop
if (ch!= ' '){
letter++;
}else { // unnecessary - you already checked space
space++;
}
i++;
}
printf("%d %d\n", letter, space);
}
Program session:
Enter a sentence: hallo my friend
you enter hallo my friend
13 2
You need to initialize i to 0 at the beginning of the program.
int i,letter,space = 0;
the above line will only set space to 0 and not i.
This shall work :
int i = 0;
int letter = 0;
int space = 0;
char ch = ' ';
printf("Enter a sentence: ");
scanf("%[^\n]s",str1);
printf("you enter %s\n",str1);
while (i!=strlen(str1)){
ch = str1[i];
if (ch!= ' '){
letter++;
} else {
space++;
}
i++;
}
You need to initialise i to 0 before entering the loop. Also if (ch=' ') should be if (ch==' '). Next time, try to compile with warnings enabled (-Wall -Wextra).
Also, while probably not related to the issue here, using strlen() in a condition of a while statement can be a performance disaster if the string is too long. Furthermore, do note that the scanf() function may write beyond the end of the buffer if the input string is too long. For this specific case, I recommend getting the string using getline() (which dynamically allocates the necessary buffer).