just starting C and want to know how to enter an unknown numbers of char into array,
when the finishing symbol will be '~'
#include <stdio.h>
#define N (499)
int main()
{
int count;
int i;
char input;
char text[N];
printf("Text:\n");
scanf("%c", &input);
while (input != '~')
{
for(i = 0; i < N; i++)
{
text[i] = input;
scanf("%c", &input);
count++;
}
}
return 0;
}
But i keep getting an infinite loop
thanks!
Remove the while loop and replace the for loop with:
for(i = 0; i < N && input != '~'; i++)
Also it is a good idea to finish your string with a terminating null character so the program knows where the string ends.
So after the for loop add:
text[i] = '\0';
Alternatively you can use some scanf regex to avoid loops alltogether.
For example:
scanf("%498[^~]", text);
will read 498 characters in the array text until the ~sign is met. It will also put the terminating character to the string.
(you should not usually use scanf, but it is good enough for a beginner)
Edit: thanks to some random guy, "amis" or smth(please tell your name) a mistake replaced.
You have 2 loops. If the first one is not elapsed (because you get less chars than N), you never return to the first one, when you test input.
More than that, the last char you read will usually be a \n, so you won't get a ~in the first loop level
If you are using count for counting initialize it to zero first.
int count = 0;
You are using for loop inside a while loop, for every character input the for loop will run N times. so check input != '~' in for loop itself, Remove while loop.
Instead of your looping method, Try this-
for(i = 0; i < N && input != '~'; i++)
{
text[i] = input;
scanf(" %c", &input); // Note the space before ' %c'
count++;
}
text[i]='\0'; // To make the last byte as null.
You need give a space before %c if you use it in loops, else you can read only N/2 input from the user!
It is due to \n after the input character. After your input when you hit enter \n is read as a next input, to avoid this give a space before %c!
Output( No space before %c )-
root#sathish1:~/My Docs/Programs# ./a.out
Text:
q
w
e
r
t
y
~
Count = 12
Output( With a space before %c )-
root#sathish1:~/My Docs/Programs# ./a.out
Text:
q
w
e
r
t
y
~
Count = 6
Note the count difference!
Related
Why does this for only runs 5 times? As in it gets 5 character and then stops. And if I change the i<10 to i<5 it only runs 3 times.
#include <stdio.h>
char a[1000];
int main()
{
char a[100];
for(int i=0;i<10;i++)
{
scanf("%c",&a[i]);
}
}
I think the problem is most likely that you don't think the Enter key will give you a character, but it will result in a newline '\n' character.
If you want to skip the newlines (or really any white-space) then use a leading space in the scanf format string:
scanf(" %c",&a[i]);
// ^
// Note space here
If you want to read other space characters (like "normal" space or tab) then you need to use one of the character-reading functions like fgetc or getchar. For example as
for (size_t i = 0; i < 10; ++i)
{
int c = getchar();
if (c == '\n')
continue; // Skip newline
if (c == EOF)
break; // Error or "end of file"
// Use the character...
}
I've encountered a problem while trying to scan chars into an array.
This is the scan loop -
char letter[6] = {0};
for(int i = 0; i <= 5; i++)
{
scanf(" %c", &letter[i]);
}
The desired result is that if the input is shorter than 6 every element which doesn't receive a value from scanf while remains 0.
However if I try to input for example 3 chars I cannot continue in the program.
On the other hand when I try to input 3 chars from txt file the program works and I achieve the desired result.
I was wondering what is the correct way to fix this issue.
Thank you all in advance.
Code fails to detect '\n' (Enter) due to space in format.
" " in scanf(" %c",&letter[i]); consumes and discards all white space including '\n' so code loses a way to detect end-of-line.
Instead check if scan failed (stdin closed or rare input error) or if a '\n' was read, then break the loop.
for(int i=0; i<=5; i++) {
char ch;
if (scanf("%c", &ch) != 1 || ch == '\n') {
break;
}
letter[i] = (char) ch;
}
To insure letter[] is a string, leave the last element as a null character.
// for(int i=0; i<=5; i++) {
for(int i=0; i < 5; i++) {
int main() {
char userInput[100]; //Store user input
//Take user input
//scanf(" %s",&userInput);
//scanf("%[^\n]s",&userInput);
//scanf("%[^\n]", &userInput);
//gets(userInput);
scanf("%[]s", &userInput); //This takes input but doesnt leave input loop
printf(" %s",userInput);
//i = index to start for looping through the string, starting at the beginning
//count = Stores occurrences of '$'
//inputLength = length of the input, used for limit of loop
int i =0,count =0;
int inputLength = strlen(userInput);
//Loop through the user input, if the character is '$', the integer count will be incremented
for (i; i < inputLength; i++){
if (userInput[i] == '$'){
count++;
}
}
printf("%d", count);
return 0;
}
Hi i'm having some issues with my code, i need to take an input of 3 lines and count the number of'$' in the input. The input method not commented "scanf("%[]s", &userInput);" is the one only i have discovered to take all 3 lines of input, BUT i can't break the input loop and continue with my program.
Any help would be greatly appreciateed
To read 3 lines with the cumbersome scanf(), code needs to look for '$', '\n', and EOF. The rest of input is discardable.
int count = 0;
int line = 0;
while (line < 3) {
scanf("%*[^$\n]"); // Scan for any amount of characters that are not $ nor \n,
// "*" implies - do not save.
char ch;
if (scanf("%c", &ch) != 1) { // Read next character.
break;
}
if (ch == '$') count++;
else line++;
}
printf("$ count %d\n", count);
As #chux suggested, reading with fgets provides a convenient way to protect from buffer overrun and without having to hard code field-width modifiers in scanf conversion specifiers.
Here, if all you need to do is count the number of '$' characters found in your input (regardless of how many lines), you can simply read ALL the input in fixed sized chunks of data. fgets does just that. It doesn't matter if you have one line, or one million lines of input. It also doesn't matter if your input lines are one-character or one million characters long. You can simply read each line and count the number of '$' found within each chunks of data read, keeping a count of the total found.
You can do this for any character. If you wanted to also count the number of line, you can simply check for '\n' characters and keep a total there as well. The only corner-case in counting lines with fgets is to insure you protect against a non-POSIX end-of-file (meaning a file with no '\n' as the final character). There are a couple of ways to handle this. Checking that the last character read was a '\n' is as good as any.
Putting the pieces together, and protecting against a non-POSIX eof, you could do something similar to the following, which simply reads all data available on stdin and outputs a final '$' and line count:
#include <stdio.h>
#define MAXC 100
int main (void) {
char buf[MAXC] = ""; /* buffer to hold input in up to MAXC size chunks */
size_t lines = 0, dollars = 0; /* counters for lines and dollar chars */
int i = 0;
while (fgets (buf, MAXC, stdin)) /* read all data */
for (i = 0; buf[i]; i++) /* check each char in buf */
if (buf[i] == '$') /* if '$' found */
dollars++; /* increment dollars count */
else if (buf[i] == '\n') /* if '\n' found */
lines++; /* increment line count */
if (i && buf[i-1] != '\n') /* protect against non-POSIX eof */
lines++;
/* output results */
printf ("input contained %zu lines and %zu '$' characters.\n",
lines, dollars);
return 0;
}
Look things over and let me know if you have further questions.
scanf("%[]s", &userInput);" is the one only i have discovered to take all 3 lines of input, BUT i can't break the input loop and continue with my program.
"%[]" is an invalid scanf() specifier. Anything may happen, it is undefined behavior, including taking all lines in and not returning.
The 's' in the format serves no purpose here - drop it.
Yes fgets() is best but let us abuse scanf() to read 3 lines and look for '$'.
char line[3][100] = {0};
// v--------- Consume all leading whitespace
// | vv ----- limit input to 99 characters as scan() appends a \0
// | || v-v-- Look for "not \n"
#define FMT_1LINE " %99[^\n]"
// Let the compiler concatenate the 3 formats into 1 string for scanf
int scan_count = scanf(FMT_1LINE FMT_1LINE FMT_1LINE, line[0], line[1], line[2]);
// Check return value
if (scan_count == 3) {
// Successfully read 3 lines
int count = 0;
for (int line_index = 0; line_index < 3; line_index++) {
char *s = line[line_index];
while (*s) { // no need for strlen(), just loop until the null character
count += *s == '$';
s++;
}
}
printf("$ count %d\n", count);
}
You write:
scanf("%[]s", &userInput); //This takes input but doesnt leave input loop
but the comment is at best misleading. Your format string is malformed, so the behavior of the scanf call is undefined. An empty scan set (between the [] in the format) does not make sense, because the resulting field could never match anything. Therefore, a ] appearing immediately after the opening ] of the scan set is interpreted as a literal character not the ending delimiter. Your scan set is therefore unterminated.
Note, too, that %[ is its own field type, separate from %s. An 's' following the closing ] of the scan set is not part of such a field descriptor, but rather an ordinary character to match.
A trivial way to do this with scanf would be to read characters one at a time in a loop via a %c field. This is probably not what the exercise is looking for, and it's a hack to use scanf() instead of getchar() for this purpose, but perhaps it would serve:
int nl_count = 0;
int dollar_count = 0;
do {
char c;
int result = scanf("%c", &c);
if (result != 1) {
break;
}
switch (c) {
case '\n':
nl_count++;
break;
case '$':
dollar_count++;
break;
}
} while (nl_count < 3);
I'm afraid it would be much more complicated to do it safely reading multiple characters at a time with a %[ field, and there is no safe way to read all three lines in one scanf call, unless you can rely on the input lines not to exceed a line length limit known to you.
int readMatrix() {
char userInput[100][3]; //Store user input
int j = 0, m = 0;
for(m = 0; m < 3; m++){
scanf("%s", &userInput[j][m]); //This takes input (Ex: 22 *(enter)* 33$ *(enter)* 66$ *(enter)*
j++; //increase the column
}
int i =0,count =0;
m = 0;
//Loop through the user input, if the character is '$', the integer count will be incremented
for (i = 0; i < 100; i++){
for(m = 0; m < 3; m++){
if (userInput[i][m] == '$'){
count++;
}
}
}
printf("%d", count);
return 0;
}
I want to write a program in C that fills an array p[MAX][N] of strings
I used this but i dont know which is the null string to enter when i give input.
#include <stdio.h>
#include <string.h>
#define R 3
#define C 8
int main()
{
int i;
char strings[R][C];
printf("***Table of Strings - Names***\n\n");
for(i=0;(i<R && gets(strings[i]));i++)
;
if(i==R)
printf("\n**Table Full - input terminated \n");
for(i=0;i<R;i++)
puts(strings[i]);
return 0;
}
First, never use gets(). It is inherently dangerous as it doesn't do any bounds checking on the memory you pass to it. Use fgets() instead:
for (i = 0; i < R && fgets(strings[i], C, stdin); ++i);
Note that fgets() will leave any new line ('\n') in the input at the end of the string, assuming that the whole line can fit in your buffer. If the whole line can't fit in your buffer, then it reads as much as can fit into your buffer (leaving room for and always appending a nul terminator), stops reading the input at that point and leaves the rest of the input on the stream. With C being so small in your program, such an occurrence is quite likely.
Alternatively, you could use getline() if it's available on your platform:
char *strings[R] = { 0 };
size_t cap;
for (i = 0; i < R && 0 <= getline(&strings[i], (cap = 0, &cap), stdin));
if (i == R)
printf("\n**Table Full - input terminated \n");
for (i = 0; i < R && strings[i]; ++i)
puts(strings[i]);
/* program done; clean up strings */
for (i = 0; i < R && strings[R]; ++i)
free(strings[R]);
getline() automatically dynamically (re)allocates the memory necessary to fit the next line from the input stream. It also leaves any new line ('\n') in the input at the end of the string.
Second, ctrl-D is typically used terminate the input to a program from a terminal.
It worked. I changed it to this
int main()
{
int i,j,max,thesi,sum=0,countCH=0,mikos=0;
char strings[R][C];
printf("***Table of Strings - Names***\n\n");
for(i=0;(i<R && fgets(strings[i],C,stdin ));i++)
;
if(i==R)
printf("\n**Table Full - input terminated \n");
for(i=0;i<R;i++)
fputs(strings[i],stdout);
//Euresh megistou string
max=0;
sum=0;
for(i=0;i<R;i++)
{
mikos=strlen(strings[i])-1;
sum+=mikos;
if(mikos>max)
{
max=mikos;
thesi=i;
}
}
printf("\nTo string me to megalitero mikos einai auto pou brisketai sthn %d seira \nkai einai to %s \nme mhkos %d",thesi+1,strings[thesi],max);
printf("\nO pinakas me ta strings periexei %d xaraktires\n",sum);
return 0;
}
It works just fine only that strlen counts all the chars of the string including null char why is that i dont get it?
Ok, i'm a student in his first experiences with programmaing so be kind ;) this is the correct code to print "n" times a string on screen...
#include <stdio.h>
#include <string.h>
#define MAX 80+1+1 /* 80+\n+\0 */
int main(void)
{
char message[MAX];
int i, n;
/* input phase */
printf("Input message: ");
i = 0;
do {
scanf("%c", &message[i]);
} while (message[i++] != '\n');
message[i] = '\0';
printf("Number of repetitions: ");
scanf("%d", &n);
/* output phase */
for (i=0; i<n; i++) {
printf("%s", message);
}
return 0;
}
why in the do-while form he needs to check if message[i++] != '\n' and not just message[i] != '\n'??
The proper way to write that input loop is, in my opinion, something along the lines of:
fgets(message, sizeof message, stdin);
in other words, don't use a character-by-character loop, just use the standard library's function that reads a string terminated by newline and be done.
The do { ... } while(...) loop in your code reads characters one at a time and stores them in message. The index of the next character is one more that the index of the previous character, that's why we should increase index variable i after the current character is stored. The algorithm is:
Read the next character and store it in message[i].
If this character is '\n', exit.
Increase i and goto 1.
The expression message[i++] increments i after it was used as an index into message, so that next time we will look at the next character in the string. So, while (message[i++] != '\n') combines steps 2 and 3.
The same in for-loop:
int i;
for (i = 0; scanf("%c", &message[i]) && message[i] != '\n'; ++i);
But as #unwind pointed, it's better not to use char-by-char input.