I am new to c programming and would like to write a program which has the following requirement:
Input: The number of inputs n, then n input chars , for example, 3 welcome to hku
Output concatenated chars, for example, welcomehku
However, I discovered a problem that when I submit the codes as following to the c autochecking platform, the output is ~~~~welcometohku instead of welcometohku.
Would anyone like to give help on the issue? Thank you very much to all of you.
#include<stdio.h>
#include<string.h>
int main(){
int num; /* array with 50 elements */
int i = 0;
char iarray1[100];
/* read array */
scanf("%d", &num);
char iarray[num][100];
for (i = 0; i < num; i++) {
scanf("%s", iarray[i]);
}
/* print array elements in reverse order */
for (i = 0; i < num; i++) {
strcat(iarray1,iarray[i]);
}
//display the concatenated string
printf("%s",iarray1);
return 0;
}
You need to initialize iarray1
Try
char iarray1[100] = {0};
The reason is that an uninitialized iarray1 may contain any value. So when you do the first strcat it may happen the string you want to concatenate is appended to some gargabe value.
Related
I have been writing a program to input a phrase and turn it into an acronym. For some reason when I output my acronym at the moment it comes out with a bunch of random characters. How do I fix it?
#include <stdio.h>
#include <string.h>
#define MAXLEN 50
int main() {
int num;
printf("Enter number of acronyms to add to the database:");
scanf("%d", &num);
getchar();
char strings[num][MAXLEN];
char acronym[num][MAXLEN];
for(int i = 0; i < num; i++){
printf("Enter the string to convert into an acronym:");
fgets(strings[i],MAXLEN,stdin);
printf("%s\n", strings[i]);
for(int j = 0; j < 11; j++){
if((strings[i][j]) >= 'A' && (strings[i][j]) <= 'Z'){
char buffer[][20] = {strings[i][j]};
strcat(acronym[i], buffer[i]);
}
}
puts(acronym[i]);
}
return 0;
}
I have tried changing the MAXLEN value to see if it was a memory issue or like a buffer overload. I've also just tried changing around how the strings switch and work together but nothing has worked.
char buffer[][20] = {strings[i][j]};
Here you let the compiler count how many elements the array has from the initialization.
It has 1 element, A string with single a single character strings[i][j] and rest of the 20 byte array filled with 0.
strcat(acronym[i], buffer[i]);
Here you access buffer[i], but there is only one string there (as explained above), so this is invalid if i is anything but 0.
I'm not sure what you are trying to do, but this would be valid implementation of what this code tries to do:
// extract single character as a string
char buffer[2] = {strings[i][j], 0}; // only one of 2 and 0 is mandatory
// append it to acronym
strncat(acronym[i], 20, buffer);
Probably lots of other stuff there is wrong, but here is one definite issue and a possible solution.
I am trying to calculate the length of a string by using a function. I know there is a predefined function but I wanted to make my own one. But the problem here is whenever I am running this code, it returns the length of the name with a %. Like this:
~ >>> /home/******/Coding/strlen
Enter your name ==> Example
The length of your name is 7%
I am really confused why this is happening. Please figure me out with what is wrong with my code... I am using GCC Version 10.2.0
/*String Length Using Function*/
#include <stdio.h>
int find_length(char[]);
int main()
{
char name[20];
int l;
printf("Enter your name ==> ");
scanf("%s",name);
l = find_length(name);
printf("The length of your name is %d",l);
return 0;
}
int find_length(char tempname[])
{
int len=0, i;
for(i = 0; tempname [i]!='\0'; i++)
{
len++;
}
return len;
}
It seems your shell is adding the % to tell you that your program didn't print a newline character at the end of output.
Add newline character to your output to prevent that.
/* add \n to print a newline character */
printf("The length of your name is %d\n",l);
I am trying to make an array of character Arrays. The program will read in sentences and store the sentences in a character array, and then that character array will be stored in another array. After reading numerous websites and Stack Over Flow pages I think it can be done like this. The program breaks when trying to store my character array into another array, so i'm not sure how to correct my code.
#include <stdio.h>
#include <math.h>
#include <time.h>
int main(int ac, char *av[])
{
int size; //number of sentences
char strings[100];// character array to hold the sentences
char temp;
printf("Number of Strings: ");
scanf_s("%d", &size); // read in the number of sentences to type
char **c = malloc(size); //array of character arrays
int i = 0;
int j = 0;
while (i < size) //loop for number of sentences
{
printf("Enter string %i ",(i+1));
scanf_s("%c", &temp); // temp statement to clear buffer
fgets(strings, 100, stdin);
// **** this next line breaks the program
c[i][j] = strings; // store sentence into array of character arrays
j++;
i++;
}
printf("The first character in element 0 is: %d\n", c[0][0]);
system("PAUSE");
return 0;
}
Al you need to do is allocate the memory for the string just read and copy the string:
c[i][j] = strings; // replace this with:
c[i]= malloc(strlen(strings)+1);
strcpy(c[i],strings);
Sadly char **c is not array of characters arrays. But this will properly allocate a 2d array dynamically if you follow
char (*c)[SIZE];
And then doing this
c = malloc(sizeof(char[LEN][SIZE]));
Then you do what you are trying to do.
for(size_t i = 0; i < LEN; i++){
if(fgets(c[i],SIZE,stdin)){
...
}
}
Or you can do it like this
char **c = malloc(LEN);
..
for(size_t i = 0; i < LEN; i++){
c[i] = malloc(SIZE);
...
}
But again c is nothing but jagged array of characters.
Check the return value of malloc and free the dynamically allocated memory when you are done working with it.
Listen dude,
Do you want to store the words in the character array and then store this in another array.
It is what you want ?
If yes then you can do the following.
Use stdlib by using # include <stdlib.h> .
This lets you use string functions directly.
Now read every word as a string and make array of strings.
So now if you number of strings is n, define an array for that as string my_array[n] and scan each word using scanf("%s",&my_array [i]).
In this way you will get an array of strings.
Wondering how store different strings in an array.
For example a user would input 'qwe' and the program would then store that in an array variable[0]. Entering another string would then store it as variable[1] and so on
int
main(int argc, char *argv[]) {
char variable[1000];
int i;
printf("enter a variable\n");
scanf("%s", variable);
for (i = 0; ??? ;i++) {
printf("The variable entered was: %s\n",variable[i]);
}
return 0;
Im new to C so I have no idea what im doing. but thats what I have came up with so far and was wondering if I could get some help with filling in the rest
Thanks!
You can use 2D array to store multiple strings. For 10 strings each of length 100
char variable[10][100];
printf("Enter Strings\n");
for (int i = 0; i < 10 ;i++)
scanf("%100s", variable[i]);
Better to use fgets to read string.
fgets(variable[i], sizeof(variable[i]), stdin);
You can also use dynamic memory allocation by using an array of pointers to char.
The most efficient way is to have an array of character pointers and allocate memory for them as needed:
char *strings[10];
int main(int ac, char *av[]) {
memset(strings, 0, 10 * sizeof(char *));
for (int i = 0; i < 10; i += 1) {
char ins[100];
scanf("%100s", ins);
strings[i] = malloc(strlen(ins) + 1);
if (strings[i]) {
strcpy(strings[i], ins);
}
}
}
variable[0] has just stored first letter of string. If you want to store multiple strings in an array you can use 2D array.
it has structure like
arr[3][100] = { "hello","world", "there"}
and you can access them as
printf("%s", arr[0]); one by one.
scanf returns number of successful readed parameters;
use 2D array for string-array
Never go out of bounds array
#include <stdio.h>
//Use defines or constants!
#define NUM_STRINGS 10
#define MAX_LENGTH_OFSTRING 1000
int main() {
char variable[NUM_STRINGS][MAX_LENGTH_OFSTRING +1 /*for '\0' Null Character */];
int i = 0;
printf("enter a variable\n");
while(scanf("%s", variable[i]) > 0){//if you print Ctrl+Z then program finish work. Do not write more than MAX_LENGTH_OFSTRING symbols
printf("The variable entered was: %s\n",variable[i]);
i++;
if(i >= NUM_STRINGS)
break;
}
return 0;
}
I will have to take the input from user and find the longest input from those 10 strings..
#include<stdio.h>
#include<conio.h>
void main() {
char str[10][10]
printf("Enter strings:")
scanf("%s", str)
}
If I take the user input like this, would it store the strings in str two dimensional array? To find out the longest string first I would find the length of each strings and use max_length function to determine the longest string.
You do not need to store all of the strings, just the longest one entered so far.
Note that you do need to define a maximum length of string to avoid buffer overrun.
For example:
#define MAX_STRING_SIZE 1024
char last_entered_string[MAX_STRING_SIZE];
char longest_entered_string[MAX_STRING_SIZE] = ""; /* Must be initialized. */
scanf("%1023s", last_entered_string); /* Read one less to allow for
null terminator. */
Use a loop to accept the ten inputs and compare with the longest string. If the last entered string is longer then copy it into the longest string. As this is homework I'll not provide any further code.
No, it won't. You have to loop through and read all strings.
for(i=0;i<10;i++)
scanf("%s", str[i]);
Also, you are missing some semi-colons!
You can find the longest string put and save it for all the string received.
int main()
{
char *str = NULL;
char *compare;
printf("Enter strings:");
scanf("%s", compare);
if (strlen(str) < strlen(compare))
str = strdup(compare);
return(0);
}
And if you want to store all of users input (considering you can have just 10 string from the user)you can do this :
int main()
{
char **array;
char *str;
int x = 0;
int shortest;
array = malloc(sizeof(char*) * 10);
while (x < 10)
{
scanf("%s", str)
array[x] = strdup(str);
x++;
}
x = 0;
shortest = x;
while (x < 10)
{
if (strlen(array[x]) > strlen(shortest))
shortest = x;
x++;
}
return (0);
}
shortest will be the index of the longest string in your array.
I hope this will help you.
Store all input in an array, then do qsort() it on the array entries length and then take the first (or the last, depending on how you sorted) entry.
Ok, ok ... - this might be over-engineered ... ;-)
The program presented will take 10 input strings from the user and then finally print out the longest string and its length. It will not store any other input strings than the biggest one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 1024
int main(int argc, char **argv){
char str_final[MAX_STR_LEN];
char str_temp[MAX_STR_LEN];
unsigned int i, j, len_str;
unsigned int num_string = 10;
unsigned int len_max = 0;
for (i=0; i<num_string; i++){
printf("Enter string number: %d\n", i);
gets(str_temp);
for (j=0; str_temp[j]; j++);
len_str = j;
if(len_str > len_max){
len_max = len_str;
memset(str_final, 0, MAX_STR_LEN);
memcpy(str_final, str_temp, len_str);
}else{
memset(str_temp, 0, MAX_STR_LEN);
}
}
printf("The biggest string is: %s\n", str_final);
printf("It's size is: %d\n", len_max);
exit(EXIT_SUCCESS);
}
I think what you can do is take a nested loop and search for a '\0' character in the row and run a counter simultaneously. as soon as you find a '\0' stop the counter and store the value of counter in a separate array . so now you will have a array of 10 integers.
Now search for smallest integer in the array and... Bingo!
The corresponding row will have the shortest string.
I know this approach is very raw but I think it will be helpful for people with only basic knowledge of C.