I am working on a program that, when specified by a number entered by the user, will only print out that number of characters. For example, if the user enters the number 10, then if 14 characters are entered (including newlines, blanks and tabs) only 10 characters will be printed. My code seems to work for the first three or so characters, then it prints out garbage. I'm not sure what is wrong.
#include <stdio.h>
#include <stdlib.h>
void findchars(char *abc, int number);
int main(void)
{
char *array; // the actual array
int num; // number of characters to read, becomes array value
printf("Number of characters:");
scanf_s("%d", &num);
array = (char *)malloc(num * sizeof(char));
findchars(array, num);
printf("The first %d characters: ", num);
puts(array);
free(array);
return 0;
}
void findchars(char *abc, int number)
{
int i;
printf("Type characters and I will stop at %d: ", number);
for (i = 0; i < number; i++)
{
abc[i] = getchar();
}
}
You are passing non-zero-terminated array to puts. If you want your program to work just create your array 1 item bigger and add '\0' in the end.
Edit: like this
array = (char *)malloc((num+1) * sizeof(char));
and then right before puts:
array[num] = '\0';
Related
I'm trying to get a number by using a getche() and then i have a functions that validates that number by getting the ascii code from it, at the same time if it gets validated it stores it in an char array, so i'm able to print it as a string, for some reason it is returning me junk. Any ideas what i'm doing wrong?
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include <string.h>
validate(int number , int size)//validates the using ASCII table and prints a string
{
char cast[size];
cast[size] = '\0'; //ads \0 to the end of the array
if((number >= 48) && (number <=57))
{
cast[size] = (char) number; //gets the number and casts it to a string
printf("\n%s", cast); //shows the number
}
}
void main(){
int numbers;
int size;
printf("\nHow many Number you want to type? : ");
scanf("%i", &size);
for(int i = 0; i < size ; i++)
{
printf("\nNumber : ");
numbers = getche();
validate(numbers, size);
}
}
I am writing a function longestStrInAr() that takes in an array of strings str and size (>0) as parameters, and returns the longest string and also the length of the longest string.
If two or more strings have the same longest string length, then the first appeared string will be
returned to the calling function.
This is the main function:
#include <stdio.h>
#include <string.h>
#define N 20
char *longestStrInAr(char str[N][40], int size, int *length);
int main()
{
int i, size, length;
char str[N][40], first[40], last[40], *p, *result;
char dummychar;
printf("Enter array size: \n");
scanf("%d", &size);
scanf("%c", &dummychar);
for (i=0; i<size; i++) {
printf("Enter string %d: \n", i+1);
fgets(str[i], 40, stdin);
if (p=strchr(str[i],'\n')) *p = '\0';
}
result = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", result, length);
return 0;
}
This is the function I have to write:
char *longestStrInAr(char str[N][40], int size, int *length)
{
int i,j, len;
*length =0;
char *longstr;
for (i = 0; i< size; i++){
j = 0;
len = 0;
while (str[i][j]!='\0'){
len++;
j++;
if (len > *length){
*length = len;
longstr = str[i];
}
}
}
return longstr;
}
My test input is
Enter array size:
4
Enter string 1:
Kenny
Enter string 2:
Mary
Enter string 3:
Peter
Enter string 4:
Sun
In XCode, I am able to receive the correct output:
longest: Kenny
length: 5
But using 2 different online compilers, I get the output below on both occasions:
longest: Kenny
length: 6
Why does my length differ?
Thank you.
probably one of them is a windows based compiler.
there "\n" is tread as two characters \r and \n
\r is called as carriage return
\n is called as line feed.
with this you get a byte extra there.
I am trying to read the number of characters including, the spaces.
I use the scanf function to check for chars using %c. Also on a side note, how would I go about storing the input into an array?
#include <stdio.h>
int main(void) {
char n, count= 0;
while (scanf("%c", &n) != EOF) {
count = count+1;
}
printf("%d characters in your input \n", count);
return 0;
}
When I test input (with spaces) such as
abcdefg
it doesn't print anything.
Defining a MAX_CHAR and checking that in loop would protect you against invalid memory write.
Remember that last byte of an array should be left for '\0', if you want to print or use the char array.
#include <stdio.h>
#define MAX_CHAR 100
int main(void) {
char n[MAX_CHAR]={0}, count= 0;
while((count!=MAX_CHAR-1)&&(scanf("%c",&n[count])==1))
{
if((n[count]=='\n')){
n[count]=0;
break;
}
count++;
}
printf("%d characters in your input [%s]\n", count, n);
return 0;
}
scanf does return EOF when it reaches the end of the file. But in order for you to see that happening, you should give your program a file input when you call it like this:
./a.out < input.txt
Inside input.txt you could put any text you want. But if you want to work in the command line, you should read until you find a \n
#include <stdio.h>
int main(void) {
char n, count = 0;
scanf("%c", &n);
while (n != '\n') {
count = count+1;
scanf("%c", &n);
}
printf("%d characters in your input \n", count);
return 0;
}
If you want to store the input in an array, you must know the size of the input (or at least the maximum size possible)
#include <stdio.h>
int main(void) {
char n, count = 0;
char input[100]; //the max input size, in this case, is 100
scanf("%c", &n);
while (n != '\n') {
scanf("%c", &n);
input[count] = n; //using count as the index before incrementing
count = count+1;
}
printf("%d characters in your input \n", count);
return 0;
}
Furthermore, if don't know the size or max size of the input, you'd have to dynamically change the size of the input array. But I think that would be a little advanced for you right now.
Your printf doesn't print anything because runtime doesn't reach to it. Your code looping for ever in while loop
while (scanf("%c", &n) != EOF) {
count = count+1;
}
because scanf won't return EOF in this case
I'm new to C and have been set the following problem. I am to write a program where a string can be entered and stored, I should then enter two integer values which will then be used to remove characters from the string, afterwards the result should be printed. Once the program works it should be converted into a function.
I have created a program that will split the entered string into two strings which store the chars I want to keep in two buffers, afterwards the two strings are concatenated to give the resultant edited string. The problem I am having is that when I print the edited string I get random characters at the end and sometimes in between the two strings and I think it's because the strings are not being null terminated correctly. I hope that someone is able to help, Thanks :)
#include <stdio.h>
#include <string.h>
int main ()
{
char string [25];
char buffer1 [25];
char buffer2 [25];
int start;
int remove;
int i;
int finish;
int size;
int numbercopy;
int A, B, C;
printf("Enter a string: ");
gets(string);
printf("\nEnter a starting character position: ");
scanf("%d", &start);
printf("\nHow many characters would you like to remove? ");
scanf("%d", &remove);
finish = (start+remove);
size = strlen(string);
numbercopy = (size-finish);
strncpy(&buffer1[0], &string[0], start);
buffer1[start] = '\0';
strncpy(&buffer2[0], &string[finish], numbercopy);
buffer2[numbercopy] = '\0';
A = strlen(buffer1);
B = strlen(buffer2);
C = (A+B);
strcat(buffer1, buffer2);buffer1[C] = '\0';
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
return 0;
}
Since it is a string, you do not need to print it character by character. Also, the loop indicates that only 25 char strings will be printed. If a string (buffer1) is shorter in length(<25), garbage values will be printed, if a string is is larger (>25), some chars will not be printed.
Change this:
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
to this:
printf("%s", buffer1);
This program is supposed to convert the array of chars (string) into an array of ints by subtracting 97 from their ascii value (the input should be lower case cause a has an ascii value of 97). So if i enter the string abcd i should get 0123 but instead I somehow get this: 012134513789. I can't figure out where the problem is.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void userEnter(int*pattern, int n);
int main(void)
{
int n, i;
printf("What is the length of the array: ");
scanf("%d",&n);
int pattern[n];
printf("Enter the char array: ");
userEnter(pattern, n);
printf("The int array is: ");
for(i=0;i<n;i++)
{
printf("%d",pattern[i]);
}
printf("\n");
}
void userEnter(int*pattern, int n)
{
char input[n];
scanf("%s", input);
int i;
for(i = 0; i < n-1; i++)
{
pattern[i] = input[i]-97;
}
}
char input[n];
scanf("%s", &input);
should be
char input[n+1];
scanf("%s", input);
input is equivalent to &input[0]
You should also exit the for loop in userEnter when you encounter the nul character that ends the user-entered string. e.g. with something like
char* p = input;
while (*p != '\0') {
*pattern = (*p) - 'a';
p++;
pattern++;
}
As KingsIndian points out, you also need to increase the size of your input buffer. At present, you overflow that buffer and overwrite the loop counter i;
The length parameter n includes one character for null as well. So, if you input length for n 4 then you can only input 3 characters, for example abc because the 4th is for the null.
So you should change the declaration accordingly:
Change:
char input[n];
to:
char input[n+1];
Note that variable length arrays are allowed only since C99.