#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
register int i;
printf("Enter an empty line to quit\n");
for(i =0 ;i<max;i++){
gets(text[i]);
if(!*text[i]){break;}
}
puts(text[1][0]);/*I want to display first character of second string but it doesn't print anything. Why??*/
}
how do i access character or part of string from array of string
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
The function gets is unsafe and is not supported by the C Standard. Instead use standard C function fgets.
The function puts expects an argument of the pointer type char * that points to a string. However you are passing an object of the type char
puts(text[1][0]);
that invokes undefined behavior.
Also declare variables in minimum scope where they are used. There is no great sense to declare the array text in the file scope.
The program can look the following way
#include <stdio.h>
#define MAX 50
#define LEN 30
int main( void )
{
char text[MAX][LEN] = { 0 };
puts( "Enter an empty line to quit" );
size_t i = 0;
while ( i < MAX && fgets( text[i], LEN, stdin ) != NULL && text[i][0] != '\n' )
{
++i;
}
if ( !( i < 2 ) ) printf( "%c\n", text[1][0] );
}
Pay attention to that the function fgets can store the new line character '\n' in the suppled array.
If you want to remove it then you can write for example
#include <string.h>
//...
text[i][ strcspn( text[i], "\n" ) ] = '\0';
In your code, puts(text[1][0]) is trying to print a text[1][0] which is a char, and puts only accepts an char*, leading to a segmentation fault on my computer.
But, printf allows you to print an char.
Fixed code:
#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
register int i;
printf("Enter an empty line to quit\n");
for(i =0 ;i<max;i++){
gets(text[i]);
if(!*text[i]){break;}
}
printf("%c\n", text[1][0]); /* printf allows you to print char */
}
Note: as said in the comments of the question, you can also use putchar() to print one character.
Input:
s
s
Output:
s
Related
My output string needs to be palindrom of the input string. It works almost perfect but I am having problem with first character of the input string, my new string won't print it (in essence my new string won't print last character). Also strrev() does not work on Ubuntu so i need to do this without using that function.
#include <stdio.h>
#include <string.h>
int main(void){
int i,j=0;
char input_str[10];
char new_str[10];
printf("Enter characters:\n");
gets(input_str);
for(i=strlen(input_str)-1;i>0;i--){
new_str[j]=input_str[i];
j++;
}
printf("Output:\n");
printf("%s", new_str);
return 0;
}
For starters the function gets is unsafe function and is not supported by the C Standard.
You should use the standard C function fgets.
There are two problems with your code. The first one is in this loop
for(i=strlen(input_str)-1;i>0;i--){
new_str[j]=input_str[i];
j++;
}
the index i equal to 0 is skipped from using it to copy the corresponding character of the source string.
The second one is the destination array is not appended with the terminating zero character.
Here is a demonstrative program that shows how a function that makes a reversed copy of a source string can be implemented.
#include <stdio.h>
#include <string.h>
char * reverse_copy( char *dsn, const char *src )
{
size_t n = strlen( src );
size_t i = 0;
for ( ; i < n; i++ )
{
dsn[i] = src[n - i - 1];
}
dsn[i] = '\0';
return dsn;
}
int main(void)
{
enum { N = 10 };
char input_str[N] = "";
char new_str[N];
printf( "Enter a string (less than %zu symbols): ", ( size_t )N );
fgets( input_str, N, stdin );
input_str[ strcspn( input_str, "\n" ) ] = '\0';
printf( "\"%s\"\n", input_str );
printf( "\"%s\"\n", reverse_copy( new_str, input_str ) );
return 0;
}
The program output might look for example the following way
Enter a string (less than 10 symbols): Hello
"Hello"
"olleH"
i is never zero. That is why the first character (input_str[0]) is ignored.
I need to read in words from a text file and then count the occurrences of each word but I can't figure out how to store the words in a variable.
I read the code in using fgets, and then i can print it using printf. However when I try to store the character array in a different array that I can use to compare the character arrays later, i keep getting seg faults. How can I go about saving the character array "line" in a different array?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 500
#define MAXWORDS 1000
int main ( int argc, char *argv[] ) {
char line[MAXSIZE];
char line1[MAXWORDS][MAXSIZE];
int i,j,k;
int count = 0;
while ( fgets ( line, MAXSIZE, stdin ) != NULL ) {
printf("%s", line);
strcpy(line1[count], line);
printf("%s\n", line1[count][i]);
count++;
}
return(0);
}
(This is my updated code, it still prints the first line and then seg faults.)
when I compile and run this code, it prints the first line of the text file and then returns "segmentation fault"
Perhaps the question code is close.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 500
#define MAXWORDS 1000
int main(int argc, char *argv[])
{
char line[MAXSIZE];
char line1[MAXWORDS][MAXSIZE];
int count = 0;
while(fgets(line, MAXSIZE, stdin))
{
printf("%s", line);
strcpy(line1[count], line);
printf("%s\n", line1[count]); // instead of: printf("%s\n", line1[count][i]);
count++;
}
return(0);
}
Your strcpy works as it should, but the printf caused a warning already at compile time, change the printf-line from printf("%s\n", line1[count]); to printf("%s\n", line1[count]);
After the while loop you can verify your copy with:
for (int i=0; i < count; i++){
printf("%d: %s",i, line[i]);
}
Although fgets will put a terminating 0-byte at the end of the buffer, it would be more defensive to user strncpy which is guaranteed not copy more than n-bytes, but in this example you could eliminate the copy altogether by writing directly in to line[count] buffer.
Also you shod take care and stop reading before overwriting your buffers.
When you call fgets you limit the read to MAXSIZE which is good but you should also check count is below MAXWORDS
A program to convert a document into an array of strings.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
main()
{
int i,j;
char *a[1000],c,*z;
z=a;
for(i=0;(c=getchar())!=EOF;i++)
{ if(c==' '||c=='\n')
{
z+=1;
i=0;
continue;
}
*(*(z)+i)=c;
}
}
I wanted to write a program to take input from the user and save the input as an array of words. But when I tried to run the code it showed the error earlier mentioned.
Thanks for the help.
Your pointer arithmetic is way off, and *a[1000] is an array of 1000 pointers, you really need something more like
int main(void) {
int i, j;
char a[1000][100], c;
i = 0, j = 0;
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\n')
{
// should null terminate if you want to treat the words as strings
a[i][j] = '\0';
i++;
j = 0;
continue;
}
a[i][j++] = c;
}
}
This should store one word (up to 99 chars, as separated by space or newline char) in each of the 1000 arrays of 100 chars that a now holds.
You should of course add checks to make sure the 99 char limit per word and 1000 word limit is never exceeded.
First of all you should use int as return type for main(), as the default return type for main() is int.
Array name is itself a pointer so remove the pointer in array declaration: char *a[1000] to char a[1000].
Now just remove the pointer from z variable in line no.18 of your code:
*(*(z)+i)=c; to *((z)+i)=c;
Hope this helps to works out the code you wanted to.
This is an unfinished code for converting alphanumeric characters into Morse code. So far only the character "A" is in set. I can't seem to copy the Morse code string of "a" into the variable "c". The compiler tells me that passing argument 1 of strcpy makes pointer from integer without a cast.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char c; /* variable to hold character input by user */
char sentence[ 80 ]; /* create char array */
int i = 0; /* initialize counter i */
const char *a = ".- ";
/* prompt user to enter line of text */
puts( "Enter a line of text:" );
/* use getchar to read each character */
while ( ( c = getchar() ) != '\n') {
c = toupper(c);
switch (c){
case 'A':
strcpy(c, a);
break
}
sentence[ i++ ] = c;
} /* end while */
sentence[ i ] = '\0'; /* terminate string */
/* use puts to display sentence */
puts( "\nThe line entered was:" );
puts( sentence );
return 0;
}
c is a single character, while a is a string (which explains both why c can only hold a single character, and why the compiler is complaining). If you want c to hold a whole string, declare it as such (like you did for sentence).
You've declared the variable c to have type char:
char c;
Then you're trying to use strcpy(c,a) -- but what type does strcpy expect for its first argument? Here's the signature from the manpage:
char *strcpy(char *dest, const char *src);
I want to print a line similar as following:
====================================
And I need to control the count of the char, and able to specify which char to print.
I don't want to use loop.
Is it possible to do this with a single printf() statement?
#Update
I ask this because I use printf in this way sometimes:
printf("%10s\n", "abc");
So, if printf could do this, then it's possible to do what I ask, I am just not sure ... now I know it can't ...
Ok, I wrote a simple util function to do this:
#include <stdio.h>
void printRepeatChar(char c, int count) {
char cs[count+1];
int i;
for(i=0; i<count; i++)
cs[i] = c;
cs[count] = '\0';
printf("%s\n", cs);
}
int main(int argc, char * argv[]) {
printRepeatChar('-', 6*4);
}
maybe use memset() from string.h instead of the direct loop makes the code shorter, just as in the answers.
And, thank you all for help.
#include <stdio.h>
#include <string.h>
void PrintStuff( char to_print, int length ) {
// adjust buffer size as desired
char buffer[256];
// -1 for null terminator
if( length > sizeof(buffer)-1 ) length = sizeof(buffer)-1;
// fill buffer with desired character
memset( buffer, to_print, length );
// add null terminator
buffer[length] = 0;
// print to output
puts( buffer );
}
int main() {
PrintStuff( '=', 11 );
return 0;
}
http://ideone.com/RjPr83
And to answer the subquestion: no, printf cannot repeat a character as a formatting rule. It can only repeat spaces or 0's when padding.
#include <stdio.h>
#include <string.h>
int main(void) {
char c='=';
char a[20];
memset(a,c,(sizeof(a)-1));
a[19] = '\0';
printf("%s\n",a);
return 0;
}
Dynamic memory allocation and character scanning can be added to this .