this is my first question on stack and I'm beginner in c.I declared a char array a[100]={"this is a test\n2nd test}.Now I'm trying to divide this array and take the two parts before and after \n as separate strings.So I declared a 2d array ab[i][k] and used a for loop to copy the characters to ab[i]. if a[j]=='\n' , I put a NULL character at the current position of ab[i][k] and increment i by 1.But for some reason, both ab[0] and ab[1] are displaying "this is a test" when I used printf to display them.Any help or suggestions would be appreciated.
int i=0;
char a[100],ab[100][100],c;
fputs(a,stdout);
printf("%d ",strlen(a));
for(j=0;j<=strlen(a);j++,k++)
{
if(a[j]=='\n')
{
ab[i][k]='\0';
k=0;
i++;
continue;
}
ab[i][k]=a[j];
}
printf("%s\n",ab[0]);
printf("%s",ab[1]);
You need to set k=-1; when you find \n, since it will be incremented at the top of the loop to 0 when you continue;.
You also need to declare int j, k=0; before the loop, to get your code to compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]) {
int i=0;
char ab[100][100];
char a[100] = "this is a test\n2nd test";
printf("%d \n",strlen(a));
int j, k=0;
for(j=0; j<=strlen(a); j++,k++) {
if(a[j]=='\n') {
ab[i][k]='\0';
k=-1;
i++;
continue;
}
ab[i][k]=a[j];
}
printf("1: %s\n",ab[0]);
printf("2: %s\n",ab[1]);
return 0;
}
23
1: this is a test
2: 2nd test
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char ar[100] = "this is a test\n2nd test\nfoobar\netc";
char sep[10][100];
int i=0;
char* token = strtok(ar, "\r\n");
while(token != NULL) {
sprintf(sep[i], "%s", token);
printf("string #%02i: `%s`.\n", i, sep[i]);
token = strtok(NULL, "\r\n");
i++;
}
return 0;
}
strtok() splits a string by any of the characters passed as a delimiter (new line and carriage return, in this case) into tokens. Passing a null pointer to the function continues where it last left off. It returns a pointer to the beginning of the token,
sprintf() saves formatted data into a variable handling \0 for you, but you could also use memcpy() or strcpy() if you like.
Related
Currently I'm reading each character from the user and storing it into a char array called str. From there I'm trying to use a pointer to loop through the string until it sees a space, once a space is seen I want to take the characters already and create an array of strings. Is that possible? Reasons why I'm doing this is because I later want to use an execlp function to execute a process after my initial program was executed.
If you want to split the string into tokens separated by delimiters you could use the strtok function.
An example would be:
#include <stdio.h>
#include <string.h>
int main(void)
{
int i, n;
char str[] = "Hello World";
char *token[4], *act_token;
token[0] = strtok(str, " ");
n=1;
while(n<4 && (act_token=strtok(NULL, " ")))
{
token[n] = act_token;
n++;
}
for(i=0;i<n;i++)
{
printf("%d: %s\n", i, token[i]);
}
return 0;
}
I'm new to C (and programming) and it's possible that my question can be answered with some basic searching and reading; please point me to an answer to the question if it exists.
Let's say that I want to read a number that can possibly be above 999 from the user. From my experience, if I enter the value 10,000 (including the comma), the program would read the number until the comma and then stop taking input. Thus, the input would be 10 instead of 10000.
How can I make it read '10,000' as if it is 10000?
#include <stdio.h>
#include <stdlib.h>
void RemoveChar(char* Number, char chartoberemoved)
{
char *p, *s;
p = s = Number;
while (*s)//Run until last \r\n
{
if (*s != chartoberemoved)
{
*p++ = *s;
}
/* We always advance s. */
s++;
}
/* We 0-terminate p. */
*p = 0;
}
int main(int argc, char* argv[])
{
char array[32];
if (!argv[1])
return -1;
strcpy(array, argv[1]);
RemoveChar(array, ',');
int num = atoi(array);
printf("%d\n", num);
return 0;
}
Most implementation of scanf and printf on Linux support ' to tell that the number may have a thousands separator:
#include <stdio.h>
#include <locale.h>
int main(int argc, char const *argv[])
{
setlocale(LC_NUMERIC, ""); // set the locale so that "," is a thousands separator
const char* string = "10,000";
float num = 0;
sscanf(string, "%'f", &num);
printf("%f\n", num);
return 0;
}
returns
10000.000000
https://www.systutorials.com/docs/linux/man/3-printf/
use strtok its information and documentation can be found here. link
I'm building a program for reversing a string in visual studio, and while I run the code and enter a word I want to reverse, the program crashes.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(" %s", r, sizeof(r));
d = strlen(r);
for (i=d;i!=0;i--) {
printf("%s",i);
}
return 0;
}
Please note that I tried your program on Linux, so no MS Visual C++ and more specifically no conio.h and gets_s.
There are multiple problems with your program:
Your call to gets_s is incorrect, according to this and this, gets_s is defined as:
char *gets_s(
char *buffer,
size_t sizeInCharacters
);
You are calling it with illegal arguments. Instead of gets_s(" %s", r, sizeof(r)); you need to call it like this:
gets_s(r, 256);
the first parameter is pointer to the string buffer where the gets_s function will store the line from input and the second is the size of the buffer, note that in char r[256] you can store 255 characters and terminating zero (\0).
Your for loop is incorrect instead of for (i=d;i!=0;i--) { you need to do it like this:
for (i=d-1;i>=0;i--) {
now the loop starts from last character instead of \0 and ends when the i < 0 ie. the last print will be when i=0.
And your final mistake is that you are using printf incorrectly instead of printf("%s",i); you need to do:
printf("%c",r[i]);
because you are printing characters: "%c" is for char output and r[i] is i-th character from string r (don't forget that we count from 0).
So, in total this is how the program should look like:
#include <stdio.h>
#include <conio.h> // does not exist on GCC (Linux)
#include <string.h>
main(void) {
char r[256]; // 255 characters + \0
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, 256); // store at most 255 characters + \0
// does not work on GCC (Linux) even with -std=C11
d = strlen(r);
// start from last character and include first
for (i=d-1;i>=0;i--) {
// %c - character, r[i] gets the i-th character from string r
printf("%c",r[i]);
}
return 0;
}
void rev(char *s)
{
char *start, *end;
end = start + strlen(s) - 1;
for (start = s; end > start; ++start, --end) {
char tmp;
tmp = *start;
*start = *end;
*end = tmp;
}
}
Use the fgets function, and also put the reversing code in its own function, like I did. So the final code is
int main()
{
char line[80];
fgets(line, 80, stdin);
/* don't allow empty string */
if (*line == '\0') {
fprintf(stderr, "Empty string is not a string\n");
return 1;
}
/* remove the \n placed by fgets */
remnl(line);
rev(line);
printf("%s\n", line);
return 0;
}
void remnl(char *s) { s[strlen(s) - 1] = 0; }
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, sizeof(r));
d = strlen(r) - 1;
for (i = d; i >= 0; i--) {
printf("%c", r[i]);
}
_getch();
return 0;
}
I want to print a line similar as following:
====================================
And I need to control the count of the char, and able to specify which char to print.
I don't want to use loop.
Is it possible to do this with a single printf() statement?
#Update
I ask this because I use printf in this way sometimes:
printf("%10s\n", "abc");
So, if printf could do this, then it's possible to do what I ask, I am just not sure ... now I know it can't ...
Ok, I wrote a simple util function to do this:
#include <stdio.h>
void printRepeatChar(char c, int count) {
char cs[count+1];
int i;
for(i=0; i<count; i++)
cs[i] = c;
cs[count] = '\0';
printf("%s\n", cs);
}
int main(int argc, char * argv[]) {
printRepeatChar('-', 6*4);
}
maybe use memset() from string.h instead of the direct loop makes the code shorter, just as in the answers.
And, thank you all for help.
#include <stdio.h>
#include <string.h>
void PrintStuff( char to_print, int length ) {
// adjust buffer size as desired
char buffer[256];
// -1 for null terminator
if( length > sizeof(buffer)-1 ) length = sizeof(buffer)-1;
// fill buffer with desired character
memset( buffer, to_print, length );
// add null terminator
buffer[length] = 0;
// print to output
puts( buffer );
}
int main() {
PrintStuff( '=', 11 );
return 0;
}
http://ideone.com/RjPr83
And to answer the subquestion: no, printf cannot repeat a character as a formatting rule. It can only repeat spaces or 0's when padding.
#include <stdio.h>
#include <string.h>
int main(void) {
char c='=';
char a[20];
memset(a,c,(sizeof(a)-1));
a[19] = '\0';
printf("%s\n",a);
return 0;
}
Dynamic memory allocation and character scanning can be added to this .
I'm making a little program in C where I would put in a couple of numbers and dots and then delete all the dots (.).
I was thinking about a whileloop but I cannot seem to quite understand what I should do next. So far I got this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
while (s[k]!=0)
{
//?????
}
return 0;
Am I on the right track or should I start differently and not use a while loop at all? I can only find solutions where there is a specific string that is not written by the user, but by the programmer...
Put in an IF to only print characters that aren't a dot. Like the others suggested, you should probably change the gets to fgets as well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
while (s[k]!=0) {
if ( s[k] != '.' ) {
printf("%c", s[k]);
}
k++;
}
printf("\n");
return 0;
}
With a while loop, I'm also worried that if the user puts in a full 30 characters, you won't reach your exit condition. To avoid this problem, a for loop would be better (since you already know the size of the array). However, if you do it this way, you'll also need to initialize your array "s" to be blank.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
for ( k = 0 ; k < 30 ; k++ ) {
if ( s[k] != '.' && s[k] != 0 ) {
printf("%c", s[k]);
}
k++;
}
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
while (s[k]!=0)
{
if(s[k] == '.')
s[k] = s[k + 1];
k++;
}
s[k] = '\0';
return 0;
#include <stdio.h>
//remove the specified character from str
char *strrmc(char *str, char ch){
char *from, *to;
from = to = str;
while(*from){
if(*from == ch)
++from;
else
*to++ = *from++;
}
*to = '\0';
return str;
}
int main(int argc, char *argv[]){
char s[30] = "192.169.007";
printf("%s\n", strrmc(s, '.'));//192169007
return 0;
}
Here's one way you might go at it - it's different from how you've started, but can easily be modified. It could be improved on as well, but we can quibble about that in further comments. :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
/* Take account number in as argument to executable */
int dotless_length = 30;
char dotless[dotless_length];
int k = 0;
int i = 0;
while (argv[1][k] != '\0' && i < dotless_length) {
if (argv[1][k] >= 48 && argv[1][k] <= 57) { /* ascii decimal codes for 0-9 */
dotless[i] = argv[1][k];
i++;
}
else if (argv[1][k] != '.') {
printf("invalid input: %c\n", argv[1][k]);
return 1;
}
k++;
}
dotless[i] = '\0'; /* null-terminate it! */
printf("Account number without dots: %s\n", dotless);
return 0;
}
Then compile with gcc -Wall -o zdotless filename.c and run with
./zdotless 401.863.3000 as an example.
Notes: This may look more harder since it goes into input sanitation (and cleanliness) a little more than your original - e.g.
not assuming that user input consists solely of numbers and periods,
saving the resulting dotless string (for presumable future manipulations?),
having one place to change the length of dotless (a step towards not hardcoding it), and
not being interactive.
When you call an executable, argv is what you've typed, so argv[0] is the executable name (./zdotless), argv[1] is the next argument (401.863.3000 as a string), and so on if there are more arguments. Since argv[1] is the string representation of your dotty input number, argv[1][0] is the first character of it, etc.
Since we're copying to dotless character-by-character rather than using string manipulation, you've got to tack on a null character manually. (That same null character is what you'd loop until reaching, when initially reading the input string.) Other questions?...