Inputting String in C programming language
1
In C programming language, the strings doesn't have a special data type on it's own. So it's usually represented with characters itself.
2
Usually an array of characters is used to represent characters like this:
3
4
``
5
int char[1000];
6
``
7
8
Characters can be read by variety of methods like:
9
10
1. scanf("%s", char);
11
12
It can read a single string, but reading strings with spaces is not supported by scanf operators
13
14
2. Then there is getline() function which is defined in C programming lanaguage book. It's actually part of
15
the build in library.
16
17
```
18
#include <stdio.h>
19
#include <string.h>
20
21
int main()
22
{
23
int bytes_read;
24
int nbytes = 100;
25
char *my_string;
26
27
puts ("Please enter a line of text.");
28
29
/* These 2 lines are the heart of the program. */
30
my_string = (char *) malloc (nbytes + 1);
31
bytes_read = getline (&my_string, &nbytes, stdin);
32
33
if (bytes_read == -1)
34
{
35
puts ("ERROR!");
36
}
37
else
38
{
39
puts ("You typed:");
40
puts (my_string);
41
printf("%d", strlen(my_string));
42
}
43
44
return 0;
45
}
46
47
```
48
49
3. There is gets() functions which is generally considered as unsafe
50
4. fgets() is more safe as it provides a bounded input
51
52
```
53
fgets(string, 1000, stdin);
54
```
55
56
For more details check [this stackoverflow answer](https://stackoverflow.com/questions/2008173/writing-secure-c-and-secure-c-idioms)
57
58
As a bonus, I am sharing how to `find Pangram of a given string in C`
59
60
{% highlight linenos %}
61
#include<stdio.h>
62
#include<string.h>
63
#define MAX_LIMIT 1000
64
65
int main() {
66
char string[MAX_LIMIT];
67
int character_hash[26]={0};
68
int pancount = 0;
69
70
fgets(string, 1000, stdin);
71
72
73
for(int i=0; i<strlen(string); i++) {
74
if('a'<=string[i] && string[i]<='z') {
75
character_hash[string[i]-'a'] += 1;
76
}
77
else if('A'<=string[i] && string[i]<='Z') {
78
character_hash[string[i]-'A'] += 1;
79
}
80
}
81
82
for(int i=0;i<26;i++){
83
if(character_hash[i]==0) {
84
pancount=1;
85
}
86
}
87
88
if(pancount==0) {
89
printf("Pangram");
90
}
91
else if(pancount==1) {
92
printf("Not Pangram\n");
93
for(int i=0;i<26;i++) {
94
if(character_hash[i]==0) {
95
printf("%c ", i+'a'); }
96
}
97
}
98
99
}
100
101
{% endhighlight %}
Copied!
Last modified 2mo ago
Copy link