Suppose I have the words: tiger, lion, giraffe.
How can I store it in a two dimensional char array using for loop and scanf and then print the words one by one using a for loop?
Something like
for(i=0;i<W;i++)
{
scanf("%s",str[i][0]); //to input the string
}
PS Sorry for asking such a basic question, but I couldn't find a suitable answer on Google.
First you need to create an array of strings.
char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];
Then, you need to enter the string into the array
int i;
for (i=0; i<NUMBER_OF_WORDS; i++) {
scanf ("%s" , arrayOfWords[i]);
}
Finally in oreder to print them use
for (i=0; i<NUMBER_OF_WORDS; i++) {
printf ("%s" , arrayOfWords[i]);
}
char * str[NumberOfWords];
str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte;
memcpy(str[0], "myliteral\0");
//Initialize more;
for(int i = 0; i < NumberOfWords; i++){
scanf("%s", str[i]);
}
You can do this way.
1)Create an array of character pointers.
2)Allocate the memory dynamically.
3)Get the data through scanf. A simple implementation is below
#include<stdio.h>
#include<malloc.h>
int main()
{
char *str[3];
int i;
int num;
for(i=0;i<3;i++)
{
printf("\n No of charecters in the word : ");
scanf("%d",&num);
str[i]=(char *)malloc((num+1)*sizeof(char));
scanf("%s",str[i]);
}
for(i=0;i<3;i++) //to print the same
{
printf("\n %s",str[i]);
}
}
#include<stdio.h>
int main()
{
char str[6][10] ;
int i , j ;
for(i = 0 ; i < 6 ; i++)
{
// Given the str length should be less than 10
// to also store the null terminator
scanf("%s",str[i]) ;
}
printf("\n") ;
for(i = 0 ; i < 6 ; i++)
{
printf("%s",str[i]) ;
printf("\n") ;
}
return 0 ;
}
Related
I have to code in an array that can count an element. For example, if the user enters a 2, 2, 2, 1,1 then the user wants to count the number 2 then the result will be ELEMENT is 2 and FREQUENCY is 3. but I have a problem with the parts of " ENTER THE NUMBER YOU WANT TO BE COUNTED". I use scanf but when I run it I cannot enter any number.
Here's my code:
void frequency()
{
system("cls");
int num;
int count=0;
printf("Enter a number you want to be count: \n ");
scanf("i%", &num);
printf(" ELEMENT | FREQUENCY \n ");
for (i = 0; i<=n; i++)
{
if (a[i]==a[num])
count++;
}
printf(" \n %i ", num);
printf(" \t\t");
printf("%i \n ", count);
getch();
}
Your program requires understanding on two parts:
Get input and split input by delimiter, which can be done by using strtok.
Algorithm for finding the duplicated elements in an array.
#include <stdio.h>
#include <string.h>
int main() {
frequency();
return 0;
}
void frequency() {
char str[100];
printf("Enter a number you want to be count: \n ");
gets(str);
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
char *pch;
int arr[20];
int count = 0;
int ncount, i, j;
int a[count], Freq[count];
while(ptr != NULL) {
/*printf("'%s'\n", ptr);*/
/*Converts the string argument str to an integer (type int)*/
arr[count] = atoi(ptr);
/*strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters*/
ptr = strtok(NULL, delim);
/*Initialize frequency value to -1*/
Freq[count] = -1;
count += 1;
}
/*Count the frequency of each element*/
for (i = 0; i < count; i++) {
ncount = 1;
for(j = i + 1; j < count; j++) {
/*Part to perform checking for duplicate elements*/
if(arr[i] == arr[j]) {
ncount++;
/*Make sure not to count frequency of same element again*/
Freq[j] = 0;
}
}
/*If frequency of current element is not counted*/
if(Freq[i] != 0) {
Freq[i] = ncount;
}
}
printf(" ELEMENT | FREQUENCY \n");
printf("-------------------------\n");
for (i = 0; i < count; i++) {
if(Freq[i] != 0) {
printf("\t%d\t\t\t%d\n", arr[i], Freq[i]);
}
}
}
Also, from your code:
You did not define i and n, which is required by your for loop. Also, since your for loop is for (i = 0; i<=n; i++), you have to define the value of n, which is the length of elements inputted by the user, in order to loop through the number of elements you expected.
int i, n, num;
...
...
for (i = 0; i<=num; i++)
Your scanf("i%", &num); should be scanf("%i", &num); instead.
You did not initialize your array a. You should have this line of code before assigning values to your array a. The value 20 can be adjusted by yourself depending on how many inputs are expected. Also, it can be coded in a flexible way instead of hardcoded as 20.
...
int i, num;
int count=0;
int a[20];
...
...
Lastly, it is a good practice to include the function's library before using it. In your case, you should include #include <conio.h> to use the getch() function.
I got this code right here, which works.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "Hello how are you";
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
but instead of char str1[100] I want to use an array of sentenceschar str1[2][100]
Meaning
char str1[2][100] = {"Hello how are you","I'm good, thanks"}
And these two sentences (or more) I want to be separated in separate words
char str1[100] = {"Hello","how","are","you"};
Actually, this is from a project for school, in which from a file, i have to store each sentence ended by '.'
If there is another way to store each sentece directly as words instead of sentences, it would be great help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LSIZ 128
#define RSIZ 10
void yodificacio(char* arr[], int index[], int n)
{
char* temp[n];
// arr[i] should be present at index[i] index
for (int i=0; i<n; i++){
temp[index[i]] = arr[i];
}
// Copy temp[] to arr[]
for (int i=0; i<n; i++)
{
arr[i] = temp[i];
index[i] = i;
}
}
int main()
{
int i = 0;
char *arr[] = {"Hey","there","how","are","you","all","today","idk"}; **Here I want the input to be char str1[2][100] = {"Hello how are you", "Im good thanks}, instead of char arr[] ...**
int index[] = {0,2,1,4,5,3,6,7};
int n = sizeof(arr)/sizeof(arr[0]);
yodificacio(arr, index, n);
printf("Reordered array is: \n");
for (int i=0; i<n; i++)
printf ("%s ", arr[i]);
return 0;
return 0;
}
Add an outer loop to process each sentence in the array.
int main()
{
char str1[2][100] = {"Hello how are you","I'm good, thanks"} ;
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
j=0; ctr=0;
for (int k = 0; k < sizeof(str1) / sizeof(str1[0]); k++) {
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[k][i]==' '|| str1[k][i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[k][i];
j++;
}
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
everyone! I decided to make an account on this site seeking for help because I could not find anything that can help me. I have a problem which requires multiple steps:
1) Read a string from keyboard;
2) Read an integer that represents the number of substrings that you want to modify ( By modifying it means to transform all of the characters of the string into " * " );
3)Read all of the substrings that need to be modified;
4) Print the initial string modified.
I tried to make it with little steps by firstly managing to do it with one substring, but I don't know how to do it when I read multiple substrings. So, here are the versions
VERSION 1
#include<stdlib.h>
#include<string.h>
int main()
{
int n;
char str[5120];
char substr[100];
printf("Type the string:\n");
gets(str);
printf("\nType the substring which you would like to modify:");
gets(substr);
char *p;
p = strstr(str,substr);
if (*p != '\0')
{
for( int j=0 ; j< strlen(substr); j++)
{
*p = '*';
p++;
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(a) ; i++)
{
printf("%c",a[i]);
}
return 0;
}
AND THE VERSION IN WHICH I TRIED TO MODIFY MULTIPLE
#include<stdlib.h>
#include<string.h>
int main()
{
int n;
char str[5129];
char substr[n][100];
printf("Type the string:\n");
gets(str);
printf("How many substrings to modify?");
scanf("%d",&n);
printf("\nType the substrings:");
for( int i=0 ; i< n ; i++)
{
scanf("%s",substr[i]);
printf(" ");
}
for ( int i=0; i < n; i++)
{
char *p;
p = strstr(str,substr[i]);
if (*p != '\0')
{
for( int j=0 ; j< strlen(cuv[i]); j++)
{
*p = '*';
p++;
}
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(str) ; i++)
{
printf("%c",str[i]);
}
return 0;
}```
I guess for the n times that I cycle to the string I have to allocate memory somewhere, or I don't know..
Please, I need some help! Thank you!
So I edited my answer based on your and #PaulOgilvie suggestions. I hope that the program now works as you expected.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 5129
void replaceSubstring(char *p, int len){
for(int i = 0; i < len; i++, p++){
*p = '*';
}
}
int main() {
int n = 0;
char str[MAX_SIZE];
char substr[n][100];
printf("Type the string:\n");
fgets(str, MAX_SIZE, stdin);
printf("How many substrings to modify?");
scanf("%d",&n);
for( int i=0 ; i< n ; i++) {
printf("\nType the substring number %d:", i+1);
scanf("%s",substr[i]);
}
char *p;
for ( int i=0; i < n; i++){
p = strstr(str, substr[i]);
while(p != NULL) {
replaceSubstring(p, strlen(substr[i]));
p = strstr(str, substr[i]);
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(str) ; i++)
{
printf("%c",str[i]);
}
return 0;
}
I am trying to solve a problem. You can ignore the problem in the code. My doubt is that if I am taking the value of t as 2, still the array outputs 3 strings although I am running the loop only t times for output.
#include<stdio.h>
#include<string.h>
int main(void){
int t;
int i;
int j;
int n;
int c;
int temp;
char result[30][3];
int flag;
scanf("%d", &t);
for(i = 0; i < t; i++){
flag = 0;
scanf("%d", &n);
scanf("%d", &c);
for(j = 0; j < n; j++){
scanf("%d", &temp);
if(c > temp){
c = c - temp;
} else{
flag = 1;
}
}
if(flag == 0){
strcpy(result[i], "Yes");
} else{
strcpy(result[i], "No");
}
}
for(i = 0; i < t; i++){
printf("%s", result[i]);
}
}
Add a \n when you printf a result[i], then you'll find that you actually output 2 strings. For example, if you first strcpy(result[0], "Yes") and then strcpy(result[0], "No"), you'll get the outputs like this:
YesNo
No
In fact, the storage of result is as follows:
result[0]: ['Y']['e']['s']
result[1]: ['N']['o']['\0']
You get "YesNo" when you output result[0], since a two-dimensional array is stored contiguously in the memory and a string ends with \0.
As another example, if you strcpy(result[0], "Hello"), then when you output result[0], you'll get
Hello
and when you output result[1], you'll get
lo
Since the storage in result is as follows:
result[0]: ['H']['e']['l']
result[1]: ['l']['o']['\0']
i'm trying to print a 2d array of string as practice(i'm a newbie) with no success i've tried every combination i could think of still nothing i'm sure i'm doing a silly error somewhere i just can't see it here some of the example:
using a pointer :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lim 10
#define maxx 25
void print(char *);
int main()
{
int i = 1;
char input[lim][maxx];
char *ps = input;
printf("type the list of %d names or type quit to leave \n", lim);
while (i<lim && gets(input[i]) != NULL && strncmp(input[i], "quit", 4)!=0 ) {
i++;
}
printf("i've counted %d names\n", i);
print("\n");
print(ps);
return 0;
}
void print(char *a)
{
int i=0;
printf("the list of names include : \n");
while(*(a) != '\0') {
printf("%s\n", *(a+i));
i++;
}
}
here's the output:
type a list of %d names or type quit to leave :
bla
bli
blo
quit
i've counted 4 names
the list of names include :
segmentation fault (core duped)
another version of the print function is like this :
void print(char aray[lim][maxx])
{
int i,j;
printf("the list of names include : \n");
for(i = 0; i < lim; i++) {
for(j = 0; j < maxx; j++){
puts(aray[i][j]);
//printf("%s\n", aray[i][j]);
}
}
}
i get the same output, can anyone help me debug this ? and thx in advance
In short, it looks like you need to brush up on your pointers. With your original print function:
void print(char *a)
{
int i=0;
printf("the list of names include : \n");
while(*(a) != '\0') {
printf("%s\n", *(a+i));
i++;
}
}
You are printing the value at a + i every iteration. This might sound like what you want, but what you actually pass to print is a pointer to an array of arrays of char (your compiler should be throwing a warning about incompatible pointer types). That is, the "proper" type of ps is (char *)[]. So in the print function you are only advancing the memory address by sizeof(char) with each iteration, whereas what you actually want is to increment it by sizeof(char) * maxx (the size of your array entries). To implement this change, do the following:
change declaration of print
void print(char (*)[maxx]);
change to proper pointer type
char (*ps)[maxx] = input;
And finally, change print function to something like:
void print(char (*a)[maxx]){
printf("the list of names include : \n");
int i;
for (i = 0; i < lim; i++){
printf("%s\n",*a);
a++;
}
}
You need not use the (a+i) syntax, as just advancing a by one each iteration accomplishes the same thing, and is possibly faster for large i. And of course, as others have mentioned, double check your new line printing, I believe you want printf('\n').
You are adding i as 1 which will not help in case of your two dimensional array as the next element will be at maxx location,so you can do something like this
//here lim and max are defined in your program
void print(char *a){
int i=0;
printf("the list of names include : \n");
while(i<(lim*maxx)){
printf("%s\n",a );
i += maxx;
a = a + maxx;
}
}
and the second variant should be
void print(char aray[lim][maxx])
{
int i,j;
printf("the list of names include : \n");
for(i = 0; i < lim; i++) {
cout<<aray[i]<<"\n";
}
}
You start on index 1 in your 2d array, you should start with index 0
int i=1;
Your print function takes an array of characters and then does a printf string of each character which makes no sense
void print(char *a)
{
int i=0;
printf("the list of names include : \n");
while(*(a)!='\0')
{
printf("%s\n",*(a+i));
i++;
}
}
instead make it look like this
void print(char *a[], int strings)
{
int i = 0;
for (; i < strings; ++i)
{
puts( a[i] );
}
}
and call it with the number of strings you read
print(ps,i);
You would also be better off using fgets() instead of gets(), especially since your strings are max 25 chars so its easy to give a longer string. fgets() lets you specify the max size of the string fgets(input[i],maxx,stdin)
Your other function
void print(char aray[lim][maxx])
{
int i,j;
printf("the list of names include : \n");
for(i = 0; i < lim; i++) {
for(j = 0; j < maxx; j++){
puts(aray[i][j]);
//printf("%s\n", aray[i][j]);
}
}
}
does a similar wrong assumption about the level of indirection
arra[i][j] is one character but puts takes a string argument, so puts( arra[i][j] ); is not correct, you could try fputc( arra[i][j], stdout ) instead since fputc takes one character
fix to
void print(char (*)[maxx]);
int main()
{
int i = 0;//int i = 1;
char input[lim][maxx] = { {'\0'}};
char (*ps)[maxx] = input;
printf("type the list of %d names or type quit to leave \n", lim);
while (i<lim && gets(input[i]) != NULL && strncmp(input[i], "quit", 4)!=0 ) {
i++;
}
printf("i've counted %d names\n", i);
printf("\n");//print("\n");
print(ps);
return 0;
}
void print(char (*a)[maxx])
{
int i=0;
printf("the list of names include : \n");
while(i<lim && a[i][0] != '\0') {
printf("%s\n", a[i]);
i++;
}
}