Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
here is my code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int x,y,i,j,k;
char c;
char n_avion[6][20]={'BOING747','AIRBUSA380','LEARJET45','DC10','ANTONOV32','CONCORDE'};
char c_avion[6][2]={'B0','AB','Lj','DC','AN','CO'};
int v_avion[6]={800,950,700,900,560,1400};
int r_avion[]={10000,12000,4500,8000,2500,16000};
printf("\nEntrer LE Code d'Avion s'il vous plait : ");
for(i=0; i<6 ;i++){
printf("%c", n_avion[i]);
}
when I try to printout n_avion using %c it gives me this päÿ¼└È
And when I try to printout n_avion using %s it gives me this 70502E
what I really want is this BOING747
Plz any help and Thanks
There are many issues:
strings must be included between " and not between '
c_avion[6][2] should be c_avion[6][3] you need one more char for the string terminator (strings are terminated by a NUL character)
printf("%c", n_avion[i]) is using the wrong format specifier for strings, it should be %s instead of %c
put a \n at the end of the printf format string, otherwise the names will be printed on a single line without spaces (try)
Corrected code:
int main()
{
int x, y, i, j, k;
char c;
char n_avion[6][20] = { "BOING747","AIRBUSA380","LEARJET45","DC10","ANTONOV32","CONCORDE" };
char c_avion[6][3] = { "B0","AB","Lj","DC","AN","CO" };
int v_avion[6] = { 800,950,700,900,560,1400 };
int r_avion[] = { 10000,12000,4500,8000,2500,16000 };
printf("\nEntrer LE Code d'Avion s'il vous plait : ");
for (i = 0; i < 6; i++) {
printf("%s\n", n_avion[i]);
}
}
BTW: my crystall ball tells be you will need to use structs sooner or later.
Other hint:
Don't use "magic numbers" like 6 or 3 but use constants.
For example:
#define NAMELENGTH 20
#define SHORTNAMELENGTH 3
#define NBOFPLANES 6
...
char n_avion[NBOFPLANES][NAMELENGTH] = ...
char c_avion[NBOFPLANES][SHORTNAMELENGTH] = ...
...
etc.
C differentiates 'x' as a character and "x" as a string ('x' and a NULL character). You want to print the strings, so use "%s" after setting your strings.
When you are trying to declare something like this
char n_avion[6][20]={'BOING747','AIRBUSA380','LEARJET45','DC10','ANTONOV32','CONCORDE'};
char c_avion[6][2]={'B0','AB','Lj','DC','AN','CO'};
I hope the intention is to define array of strings, in which case values needs to be in double quotes.
char n_avion[6][20]={"BOING747","AIRBUSA380","LEARJET45","DC10","ANTONOV32","CONCORDE"};
char c_avion[6][2]={"B0","AB","Lj","DC","AN","CO"};
having said that a string is a character array terminated with '\0' character
however here, there is no space for '\0' character at all because the size is restricted to 2 as defined in char c_avion[6][2], so make some room for '\0'
char c_avion[6][3]={"B0","AB","Lj","DC","AN","CO"};
finally the printf
simply put "%s" is for strings and "%c" for characters
Related
I have confusion on char* null-termination so i have decided to make a study of cases i can find. Do these string literals end with a null?
char str1[512]="This is a random string"
char *str2 = strtok(buffer,"\n,") I have found its answer. This ends with null.
fgets(stdin, str3, 512)
scanf("%s",str4)
The code snippet:
char str[5];
for(int i=0; i<5; i++) scanf("%c",&str[i]);
Note 1: I have an assumption that all standard functions in c library that returns a char*, null terminates the string.
Note 2: How do I check if a string is null terminated or not? (I tried this approach but it prints random stuffs imo.)
Edit: Just showing me a way to determine whether a string literal is null-terminated will be enough. I will go through each case and update here for future readers.
Such an example is by no means exhaustive, but it brings some clarity. The answer is actually simple. Any array of characters ending in '\0' is called a string. The programmer independently decides what he needs .
#include<stdio.h>
int main(void)
{
char w[]="mamamia";
int i;
for(i=0;i<sizeof(w);i++)
{
if(w[i]=='\0')
printf("w[%d]==null\n",i);
else
printf("w[%d]== %c \n",i,w[i]);
}
return 0;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am a newbie to C Language. For a my assignment, I wrote this simple code to Print the student grade according to the input marks.
main(){
char grade;
grade = grade_calc(90);
printf("Your Grade is ", grade);
}
char grade_calc(int marks){
if(marks >= 75){
return "A";
}
else {
return "B";
}
}
But it shows error in Function starting line (int marks).
functions.c [Warning] return makes integer from pointer without a cast
Can anyone help me, why it this error happens?
This should do it.
int main(){
char grade;
grade = grade_calc(90);
printf("Your Grade is %c", grade); //%c specify char
// ^^
}
char grade_calc(int marks){
if(marks >= 75){
return 'A';
// ^ ^
}
else {
return 'B';
// ^ ^
}
}
In case you want to know more: C format specifiers.
Also, your return type is conflicting(char vs char*).In case you don't know, "A" is a char* (string) and 'A' is a char (you can learn more about the differences here
. Last but not least, don't forget that main() return int and functions need to be defined before used.
This is the declaration of printf
int printf(const char *format, ...)
printf takes the arguments (what you send to it in the parenthesis) and print it on the screen.
but, printf need to know where to print from (aka what bits you want to print), when to stop and which format are we talking about.
for example:
if we takes a int printf needs to know where is it to see its value.
which type it (int) so printf know to stop printing after 4 bytes. and again the type(int) so the bits will represent as numbers and not chars or floats
every type has its wildcard:
%d for int
%c for char
%s for strings
%f for float
you can look it up
also you need to return a char from the function
so you need to return this:
return('a'); and not return ("a");
so,
"a"
means string literal so the function returns char * and not char.
'a'
means value of the char a
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am a beginner to c language. Please help me to find the error of the code as it gives a complilation error on the display.
#include <stdio.h>
#include <string.h>
void main()
{
char i;
char arr[23];
printf("Enter your name? \n");`
scanf("%c",&arr[i]);
for(int v=0;v<=strlen(arr);v++)
{
printf("%c",arr[v]);
}
}
Your code has several issues, not only one:
1.
You use the wrong format specifier %c to catch a single character instead of %s to catch a string:
char arr[23];
printf("Enter your name: \n");`
scanf("%c",&arr[i]);
Rather use scanf("%s",arr); or even better scanf("%Ns",arr); where N stands for the maximum number of characters to be entered. Note that you need one element for the string-terminating null character, so it requires to be at least one character less than the char array is consisted of.
You can also use fgets(arr,23,stdin) which is preferred for consuming strings from the standard input because it is more safe as it requires you to provide the maximum amount of characters to read (counting the null character too) and also reads white space separated words as part of the string by default.
2.
i is not initialized to any value, so:
scanf("%c",&arr[i]);
causes undefined behavior.
3.
Furthermore you try to get a string length by using strlen() as part of the condition expression of the for loop:
for(int v = 0; v <= strlen(arr); v++)
although there is no valid string in arr which causes also undefined behavior.
As a side note here: It is more efficient to use strlen() only once before the for loop, store its return value in an object of an appropriate type (size_t is the type of the return value of strlen()) and use that object in the condition of the for loop instead of executing strlen() before each iteration.
4.
Next thing is that you attempt to print characters inside the for loop which aren´t provided/initialized to arr:
for(int v = 0; v <= strlen(arr); v++)
{
printf("%c",arr[v]);
}
5.
The for loop with the condition v <= strlen():
for(int v = 0; v <= strlen(arr); v++)
runs one time more than expected and prints the null character which is redundant since the null character is not printable.
Rather use v < strlen() or according to point 3:
size_t len = strlen(arr);
for(int v = 0; v < len; v++)
6.
The return value of main shall be int, not void.
7.
There is a trailing apostrophe after the printf() call:
printf("Enter your name: \n");`
Rather use:
#include <stdio.h>
int main()
{
char arr[23];
printf("Enter your name: \n");
scanf("%22s",arr);
printf("%s",arr);
}
Online Example
if you want to print out the string entered as whole at once, or:
#include <stdio.h>
#include <string.h>
int main()
{
char arr[23];
printf("Enter your name: \n");
scanf("%22s",arr);
size_t len = strlen(arr);
for(int v = 0; v < len; v++)
{
printf("%c",arr[v]);
}
}
Online example
if you want to print each character separate.
Your error is not really an error. You have an extra character in this lane:
printf("Enter your name? \n");`
It should be:
printf("Enter your name? \n");
There is a ` at end of the line
printf("Enter your name? \n");`
note you are using uninitialized int i here scanf("%c",&arr[i]); which is wrong.
also with scanf("%c",&arr[i]); you can only scan one character for string arr which I think is not your purpose.
you can use scanf("%s",arr[i]); instead to appropriately scan an string .
also note when ever you are scanning string char by char you have to add terminator \0 to the end of your string.after scanning characters until element i-1 of array add \0 to element i like this arr[i]=\0;.
since your string isn't terminated appropriately strlen won't work well.
also note you should print elements of string while v<strlen(arr) the last char should be \0 so you should use in for(int v=0;v<=strlen(arr);v++)
also pay attention to use int main not void main.
look:
void main()
{
char arr[23];
printf("Enter your name? \n");
scanf("%s",arr);
for(int v=0;v<strlen(arr);v++)
{
printf("%c",arr[v]);
}//or instead of loop use printf("%s",arr);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Ethernet starter kit(PIC32MX9795F512L)
language: C
MPLAB IDE 8.92
Compiler: XC32 v1.3
Hello i want to add leading zeros to my variables. At the end i want to use the in an array.
For example: c=10*a+b. When c=5 it should be 05. I cant use any printf function or am I wrong?
You can use printf() to simply print a formatted number to standard output:
int c = 5;
fprintf(stdout, "c [%02d]\n", c);
If you can't use printf(), another option is to store the padded value in a char * or string. You can instead use sprintf() to write the formatted string to a char * buffer.
For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]) {
{
char* c_str = NULL;
int c_int = 5;
int c_str_length = 3; /* two bytes for "0", "5", and one byte for the nul terminator */
c_str = malloc(c_str_length);
if (!c_str) {
fprintf(stderr, "Error: Could not allocate space for string!\n");
return EXIT_FAILURE;
}
int n = sprintf(c_str, "%02d", c_int);
if (n != c_str_length) {
fprintf(stderr, "Error: Something went wrong in writing the formatted string!\n");
free(c_str);
return EXIT_FAILURE;
}
fprintf(stdout, "c_str: [%s]\n", c_str);
free(c_str);
return EXIT_SUCCESS;
}
If you go this route, you can see how you could do some error checking along the way. You'll need to think about string length (hint: log10()), or use a static char [] array in place of a char * of sufficiently long length.
It is quite easy to add a leading zero, provided you take care of negative values too. You said you want to write to an array, so I used sprintf but if you want to output directly, you can use printf in a similar way.
char cstr[24];
int c = 10 * a + b;
if (c > 0) {
sprintf(cstr, "0%d", c);
} else if (c < 0) {
sprintf(cstr, "-0%d", -c);
} else {
//sprintf(cstr, "00");
sprintf(cstr, "0"); // depending on your needs
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to learn C programming by reading a textbook, but am confused about how strings and substrings work.
I have an idea of what strings and substrings are from java, but can't figure out the syntax in C.
Here's a question from the book that I thought might be easy, but I can't get it.
Write and test a function hydroxide that returns a 1 for true if its string argument ends in the substring OH.
It recommends testing the function with KOH and NaCl.
Also, how would I remove and add letters at the end of the string?
Like, if for some reason I wanted to change NaCl to NaOH?
Any help and explanations would be really appreciated.
ETA:
I guess what I'm most confused on is how to make the program look at the last two letters in the string and compared them to OH.
I'm also not sure how to pass strings to functions.
String is a sequence of characters that ends with special null-terminated character '\0'. If there is no \0, functions that work with string won't stop until the \0 symbol is found. This character may happen in any place after the end of pseudo string (I mean a string without \0) and only then stop.
The following example shows the necessity of this null-terminated character:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[] = "Hello!";
printf("original string:\n%s\n\n", string);
memset(string, '-', 5);
printf("memset doesn't affect the last two symbols: '!' and '\\0':\n%s", string);
memset(string, '-', 6);
printf("\n\nmemset doesn't affect the last symbol: '\\0':\n%s\n\n", string);
memset(string, '-', 7);
printf("memset affects all symbols including null-terminated one:\n%s", string);
return 0;
}
/* OUTPUT:
original string:
Hello!
memset doesn't affect the last two characters: '!' and '\0':
-----!
memset doesn't affect the last character: '\0':
------
memset affects all characters including null-terminated one:
-------#↓#
*/
Substring is a char sequence that is in a string. It may be less or equal to the string.
Suppose, "NaOH" is a string. Then substring may be: "N", "a", "O", "H", "Na", "aO", "OH", "NaO", "aOH", "NaOH". To find whether substring is in the string or not you can use strstr function. It's prototype is char * strstr ( char * str1, const char * str2 );.
This code shows this function's results:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *ptrCh = NULL;
ptrCh = strstr("hello", "h");
printf("ptrCh: %p\n", ptrCh);
printf("%s\n\n", ptrCh);
ptrCh = strstr("hello", "z");
printf("ptrCh: %p\n", ptrCh);
printf("%s\n\n", ptrCh);
return 0;
}
/* OUTPUT:
ptrCh: 00403024
hello
ptrCh: 00000000
(null)
*/
As for the first printf, it prints characters beginning from the position of 'h' and when it reaches null-terminated character, which is next after 'o', it stops, exactly as in previous program.
To make your program more interactive, you can declare array and then a pointer to it. Array size must be enough to store the longest formula. Suppose, 100 will be enough:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[100] = {0};
char *ptr = &buf[0];
scanf("%s", ptr);
// printf() gets a pointer as argument
printf("%s\n", ptr);
// printf() gets also a pointer as argument.
// When you pass arrays name without index to a function,
// you pass a pointer to array's first element.
printf("%s", buf);
return 0;
}
And as for rewriting letters in the end of the string. Here is a small program that does it. Pay attention at comments:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[100] = {0};
char formula[100] = {0};
char compound[100] = {0};
char *ptr = &buf[0];
char *pFormula = &formula[0];
char *pCompound = &compound[0];
printf("Enter formula: ");
scanf("%s", pFormula);
printf("Enter chemical compound: ");
scanf("%s", pCompound);
// Copying the first chemical elements without the last
// several that will be replaced by another elements.
strncpy(ptr, pFormula, strlen(pFormula) - strlen(pCompound));
// Adding new compound to the first elements.
// Function also adds a null-terminated character to the end.
strncat(ptr, pCompound, strlen(pCompound));
printf("The new chemical compound is: ");
printf("%s", ptr);
return 0;
}
/* OUTPUT:
Enter formula: NaOH
Enter chemical compound: Cl
The new chemical compound is: NaCl
*/
In C, we use null-terminated strings. That is the "invisible", 0 value. Not ASCII "0", but the zero value, like 8-bit 0x00. You can represent it in literal text with '\0' or "\0" or unquoted 0, however, in a literal string it is redundant because most functions like strcmp() or strstr() or strcat() all expect and work with null terminated strings. Null char is the stops sign for the C standard string functions.
One easy way to implement this with C library calls is to test for existence of the substring and then test that substring's length, which verify it is at end of string.
Assume buf is some big string buffer, char buf[1024] and char *temp is a temporary variable.
temp = strstr(buf, "OH") returns the pointer to "OH" if exists in buf at any offset.
strlen(temp) Get length of temp, if at end of string, it will be 2 (doesn't include null terminator), so if the original string is "OHIO" or "SOHO" it wont match because it'll be 4 and 3 respectively.
The above is the core of the code, not the full robust implementation. You need to check for valid return values, etc.
char buf[1024];
char *temp;
strcpy(buf, "NaOH");
if((temp = strstr(buf, "OH")) != 0)
{
// At this point we know temp points to something that starts with "OH"
// Now see if it is at the end of the string
if(strlen(temp) == 2)
return true; // For C99 include stdbool.h
return false;
}
You could get obscure, and check for the null terminator directly, will be a smidge quicker. This code is safe as long as it is inside the if() for strstr(), otherwise never do this if you don't know a string is a least N characters long.
if(temp[2] == '\0')
return true; // For C99 include stdbool.h
As far as appending to a string, read the docs on strcat. Keep in mind with strcat, you must have enough space already in the buffer you are appending into. It isn't like C++ std::string or Java/C# string where those will dynamically resize as needed. In C, you get to do all of that yourself.