Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to properly print each element in a c string?

Tags:

c++

string

#include <stdio.h>
#include <iostream>

using namespace std;

int main(){
    char *a[20];
    FILE * fin = fopen("testtest.txt","r");
    int i;

    fscanf(fin,"%s",a);

    for(i=0;i<20;i++)
    {
        printf("%c\n",a[i]);
    }

    system("pause");
}

In this program, I suppose to print each element in the array, which should be A B C D E but actually it prints:

It seems every element is weired, how should I print it correctly?

A
E
─
╒
┴
■
┌
·
Φ

8
↔


p
╘
╠
x
3
☻
like image 425
Coderzelf Avatar asked Dec 01 '25 06:12

Coderzelf


2 Answers

The type of a is an array of char*, not an array of char. Change to:

char a[20];

Recommend compiling at the highest warning level and treat warnings as errors. For example:

$ gcc -Wall -Werror -pedantic main.c
main.c: In function ‘main’:
main.c:9:5: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Werror=format]
main.c:10:5: error: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Werror=format]
cc1: all warnings being treated as errors

Check the result of fopen() and fscanf() to be certain the file was opened and data was read into a before attempting to use the variables.

like image 183
hmjd Avatar answered Dec 03 '25 21:12

hmjd


a is an array of 20 char pointers. I think you wanted an array of 20 chars instead

char a[20];
like image 26
simonc Avatar answered Dec 03 '25 19:12

simonc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!