I currently have this program that prints a text file on the console, but every line has an extra new line below it.
if the text was
hello
world
it would output
hello
world
the code is this
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
FILE* fp;
char input[80], ch = 'a';
char key[] = "exit\n";
int q;
fp = fopen("c:\\users\\kostas\\desktop\\original.txt", "r+");
while (!feof(fp)) {
fgets(input, 80, fp);
puts(input);
}
fclose(fp);
return 0;
}
Typically one would use fputs() instead of puts() to omit the newline. In your code, the
puts(input);
would become:
fputs(input, stdout);
puts() adds the newline character by the library specification. You can use printf instead, where you can control what gets printed with a format string:
printf("%s", input);
You can also write a custom puts function:
#include <stdio.h>
int my_puts(char const s[static 1]) {
for (size_t i = 0; s[i]; ++i)
if (putchar(s[i]) == EOF) return EOF;
return 0;
}
int main() {
my_puts("testing ");
my_puts("C puts() without ");
my_puts("newline");
return 0;
}
Output:
testing C puts() without newline
This should work:
#include<stdio.h>
void put_s(char* s){
while(*s) putchar(*s++);
}
Just for the sakes of having more examples, here is another one involving recursion:
#include<stdio.h>
void put_s(char* s){
if(!*s) return;
putchar(*s);
put_s(s+1);
}
Note: I noticed that your code wouldn't compile, because of the #include<iostream> and the using namespace std;.
Related
My file contains three lines, after using fgets to read the file into an array, I want to break the three lines at the new line character and print the three lines separately out on the console and if possible store the three lines in three different arrays.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *infile;
char data[BUFSIZ],*pa,token_seperator[]={"\n"};
infile=fopen("example","r");
while((fgets(data,BUFSIZ,infile)!=NULL))
pa=strtok(data,token_seperator);
while(pa!=NULL)
{
printf("%s\n",pa);
pa=strtok(NULL,token_seperator);
}
}
There is no any sense "to break the three lines at the new line character" because a line can contain no more than one new line character.
If you need to read each line in a separate array then just declare a two-dimensional character array. If you want you can remove the new line character appended to each line by the call of fgets.
So the program can look the following way.
#include <stdio.h>
#include <string.h>
#define N 3
int main( void )
{
FILE *infile;
char data[N][BUFSIZ];
infile = fopen( "example", "r" );
if ( infile )
{
size_t n = 0;
for (; n < N && fgets(data[n], BUFSIZ, infile); n++)
{
data[n][strcspn(data[n], "\n")] = '\0';
}
for (size_t i = 0; i < n; i++)
{
printf("%s\n", data[i]);
}
}
return 0;
}
The function below,truncCrLf, deletes from ASCII-0 strings the first occurence of the CR and/or LF codes. This is what you are looking for because the fgets function reads from the file till these ASCII codes (0xA and/or 0xD).
This function acts under both Linux and Windows SO.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * truncCrLf(char *data)
{
char *app=NULL;
app = strchr(data, '\n');
if (app)
*app=0;
app = strchr(data, '\r');
if (app)
*app=0;
return data;
}
int main(void)
{
char test[200];
strcpy(test,"Hello world\n");
printf("%s......\n",test);
truncCrLf(test);
printf("%s......\n",test);
return 0;
}
You will need allocate some memory to do this, just because you don't know how many line you finally will have nor the size of each one.
I suggest you the next code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef SplittedString char[BUFSIZ]
int main()
{
FILE *infile;
char token_seperator[]={"\n"};
SplittedString data;
SplittedString myLines[50]; // you can modify this number to hold more lines
int i=0;
infile=fopen("example","r");
while((fgets(data,BUFSIZ,infile)!=NULL) && i < 50){ //prevent array overflow
printf("%s\n",data);
strcpy(myLines[i], data);
++i;
}
}
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;
}
Below is my piece of code, I don't understand why it always gives me the segmentation fault:
#include <stdio.h>
void reverse(void);
int main ()
{
printf("enter the text");
printf("\n");
reverse();
printf("\n");
return(0);
}
void reverse(void)
{
char c;
if((c=getchar()) != '\n')
{
reverse();
}
putchar(c);
}
In my opinion I have done everything correctly, what is the mistake?
The code works fine as long as you enter a newline. Perhaps you are terminating your input with EOF (usually bound to Ctrl+D) without feeding it a newline before, and in that case, the code will never see a newline and there will be a stack overflow due to infinite recursion.
So, you should check that getchar() doesn't return EOF. Also, getchar() returns int, not char - this is important for portability and to make sure that comparison with EOF works as expected.
Here's the code after addressing these issues:
#include <stdio.h>
void reverse(void);
int main (void) {
printf("enter the text\n");
reverse();
printf("\n");
return 0;
}
void reverse(void) {
int c;
if ((c=getchar()) != '\n' && c != EOF) {
reverse();
}
if (c != EOF) {
putchar(c);
}
}
Your program compiled and ran fine on my setup: latest stable gcc on Ubuntu 14.04.2 LTS 64-bit.
Here is another version using a different approach (namely the fgets function). See if it works for you:
#include <stdio.h>
#include <string.h>
void reverse_str( char * );
int main()
{
char input[1024];
printf("Enter text: ");
fgets(input, sizeof(input), stdin);
reverse_str(input);
printf("Reversed string: %s\n", input);
return 0;
}
void reverse_str(char *to_reverse)
{
char temp[1024];
int count = strlen(to_reverse) - 1; //Exclude newline introduced with fgets
int i=0;
for( i=count; i>=0; i-- ){
temp[i] = to_reverse[count - i - 1]; //Subtract 1 to not include the new line introduced by fgets
}
temp[count+1] = '\0';
strcpy(to_reverse, temp);
}
Your code seems to failing because of the nasty characters of getchar()..In most of the system it should work but I think your compiler is trying to access the memory saved beyond the array & hence generating segmentation fault...Can you please make sure if you give '\0' in place of '\n', it is working or not..I think the problem is that your machine is not able to detect the '\n' given from your keyboard & hence keep on going into recursion mode & stack is overflown before the recursion ends & when stack is overflown, it is trying to access unauthorised memory & hence segmentation fault occurs
Try this
#include <stdio.h>
#include <string.h>
char str[] = "Hello World";
size_t length;
int count = 0;
void reverse(char* a, char* b){
// static int count = 0;
char temp;
if (count < length/2){
count++;
reverse(str + count, str + (length - 1) - count);
}
temp = *a;
*a = *b;
*b = temp;
}
int main(){
length = strlen(str);
reverse(str, str + length - 1);
printf("%s", str);
return 0;
}
#include <Windows.h>
#include <cstdio>
const int KEY=111;
void encryptStrA(char* sometext)
{
int length;
length=strlen(sometext);
for(int i=0; i<length;i++)
sometext[i]^=KEY;
}
int main(void)
{
FILE* pFile=fopen("pliczek","wb");
char sign;
char sampleString[]="Hello world!";
encryptStrA(sampleString);
fprintf(pFile,"%c%c%s%c%c",13^KEY,10^KEY,sampleString,13^KEY,10^KEY);
fclose(pFile);
pFile=fopen("pliczek","rb");
while(!feof(pFile))
{
fscanf(pFile,"%c",&sign);
printf("%c",sign^KEY);
}
fclose(pFile);
system("PAUSE");
return 0;
}
I evaded some tricky things
File is opened in binary mode
In encryptStrA strlen function isn't placed directly in the loop condition
In spite of these, it still has been outputting "Hell" instead of "Hello World!"? More precisely, cuts everything after spotting the key character .What's the reason? I use OS in which every line of text is ended with carriage return(ASCII 13) and line feed (10).
The code fprintf("%s", s); expects s to be a zero-terminated string. When you reach 'o'^111 it gives a null character, so the rest of the string is not written to the file.
You can use fwrite instead.
I am a C beginner and this is my C code:
#include <stdio.h>
#include <stdlib.h>
main()
{
printf("Hello, World!\n");
return 'sss';
}
That will show an error. So how can I return a string in C code?
If you are looking to return a string from a function (other than main), you should do something like this.
#include <stdio.h>
const char * getString();
int main()
{
printf("Hello, World!\n");
printf("%s\n", getString());
return 0;
}
const char * getString()
{
const char *x = "abcstring";
return x;
}
The magic is in the key word static which preserves the memory content of the string even after the function ends. (You can consider it like extending the scope of the variable.)
This code takes one character each time, then concatenates them in a string and saves it into a file:
#include <stdio.h>
#include <conio.h>
char* strbsmallah ()
{
static char input[50];
char position = 0, letter;
scanf("%c", &letter);
while (letter != '~') { // Press '~' to end your text
input[position] = letter;
++position;
scanf("%c", &letter);
}
input[position] = '\0';
char *y;
y = (char*) &input;
//printf("%s\n ", y);
return y;
}
int main() {
printf("\n");
FILE *fp;
fp = fopen("bsmallah.txt", "w+");
fprintf(fp, strbsmallah());
while (!_kbhit())
;
return 0;
}
You could do this in a way similar to scanf. In other words:
void foo(char **value_to_return) {
*value_to_return = malloc(256); // Store 256 characters
strcpy(*value_to_return, "deposited string");
}
int main() {
char *deposit;
foo(&deposit);
printf("%s", deposit);
return 0;
}
You don't return a string. Applications exit with an integer exit code.
Conventionally, exiting with a return of 0 will always show that your application exited without error / completed. You return an integer other than 0 to show that your application exited abnormally.
You could throw an exception and handle it with a logging method higher in the call stack, or you could just return something other than 0 and make sure you had it documented in your release notes as to what each error integer means.
Sadly there is no way to do that.
You could add something to the end of your C program like:
int main()
{
int err = 0; // 0 is "success" is most C programs
printf("Hello, World!!\n");
switch( err )
{
case 0:
printf("Program shutdown successfully!\n");
break;
case 1:
printf("We had an issue somewhere. Please fix your input data\n");
break;
//case 2, 3, etc...
};
return err;
}
You might be able to use environment variables for that. Not sure though.