Equivalent of C++ cin.tie() for C stdio? [duplicate] - c++

I'm using Eclipse to code in C/C++ and I'm struggling with what might be something pretty easy. In my code below I use printf() and after scanf(). Althougth printf is written before scanf() the output differs. I was able to find out something about similar issue here. But I wasn't able to solve it. Any ideas?
Code:
#include <stdio.h>
int main()
{
int myvariable;
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
Expected output:
Enter a number:1
1
Instead I get:
1
Enter a number:1

Your output is being buffered.
You have 4 options:
explicit flush
fflush after each write to profit from the buffer and still enforce the desiredbehavior/display explicitly.
fflush( stdout );
have the buffer only buffer lines-wise
useful for when you know that it is enough to print only complete lines
setlinebuf(stdout);
disable the buffer
setbuf(stdout, NULL);
disable buffering in your console through what ever options menu it provides
Examples:
Here is your code with option 1:
#include <stdio.h>
int main() {
int myvariable;
printf("Enter a number:");
fflush( stdout );
scanf("%d", &myvariable);
printf("%d", myvariable);
fflush( stdout );
return 0;
}
Here is 2:
#include <stdio.h>
int main() {
int myvariable;
setlinebuf(stdout);
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
and 3:
#include <stdio.h>
int main() {
int myvariable;
setbuf(stdout, NULL);
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}

Ok, so finally I used something similar to what #zsawyer wrote as an option labelled 3.
In my code I inserted this line:
setvbuf(stdout, NULL, _IONBF, 0);
As a first line in main():
#include <stdio.h>
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
int myvariable;
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
I got it from here.

Related

C++ - my program stops running `freopen` function from <cstdio>

In my main.cpp:
#include <cstdio>
#include "hashtable.h"
int main() {
printf("1hello");
freopen("2.txt", "w", stdout);
printf("2hello");
freopen("1.txt", "r", stdin);
printf("3hello");
int type;
char buffer[1000];int data;
hashtable table(10000, new naive_hashing(), new linear_probe());
while (true) {
scanf("%d", &type);
if (type == 0) {
scanf("%s", buffer);scanf("%d", &data);
table.insert(hash_entry(buffer, data));
}
else if (type == 1) {
scanf("%s", buffer);
printf("%d\n", table.query(buffer));
}
else break;
}
return 0;
}
1.txt:
0 dhu_try 3039
0 shirin 3024
0 SiamakDeCode 2647
0 huanghansheng 233
1 dhu
1 dhu_try
1 shirin
1 siamakdecode0
1 huanghansheng
2
output:
1hello
As you can see the program paused after it entered the first freopen function. I have checked the document already and still yet cannot find the reason why it stopped running. Can anyone help me please? :pleading_face:
You redirected all output to stdout to the file 2.txt when you did
freopen("2.txt", "w", stdout);
That's why no printf outputs are shown on the console after that freopen. Look in the file 2.txt and you will most probably see the output there - if the freopen succeeded. Always check if functions that can fail have succeeded.

OS X move terminal caret with arrow keys

I made a simple C programme that demonstrates the issue. Here it is.
#include <stdio.h>
int main(int argc, const char * argv[]) {
char buffer[128];
memset(buffer, 0, sizeof(buffer));
printf("Type data:\n");
scanf("%126s", buffer);
printf("%s\n", buffer);
getchar();
return 0;
}
The problem is that when the application is waiting for user input with scanf() and user user wants to edit line he typed, and to do move caret with arrows, the caret is not moving but new ugly input is inserted.
For some reason it does not handle the keys in a way I expect. I'm not able to go to the previous typed line with the up key, as well.
Obviously I should deliberately enable this behaviour. Could you advice, how can I do that?
Use readline(). Here's a simple example:
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <ctype.h>
#define MAX_LINE_LEN 80
int main() {
char *line_buffer;
int n, i;
while (1) {
line_buffer = readline("Say something: ");
if (!line_buffer) break;
for (i=0; line_buffer[i]; i++) {
line_buffer[i] = toupper(line_buffer[i]);
}
printf("YOU SAID: %s\n",line_buffer);
}
putchar('\n');
return 0;
}
/* (Compile with cc foo.c -lreadline -o foo) */

How to clear input in C++ Console commands [duplicate]

Is there any way to hide user input when asked for in C?
For example:
char *str = malloc(sizeof(char *));
printf("Enter something: ");
scanf("%s", str);getchar();
printf("\nYou entered: %s", str);
// This program would show you what you were writing something as you wrote it.
// Is there any way to stop that?
Another thing, is how can you only allow certain characters?
For example:
char c;
printf("Yes or No? (y/n): ");
scanf("%c", &c);getchar();
printf("\nYou entered: %c", c);
// No matter what the user inputs, it will show up, can you restrict that only
// showing up if y or n are entered?
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)
int set_disp_mode(int fd,int option)
{
int err;
struct termios term;
if(tcgetattr(fd,&term)==-1){
perror("Cannot get the attribution of the terminal");
return 1;
}
if(option)
term.c_lflag|=ECHOFLAGS;
else
term.c_lflag &=~ECHOFLAGS;
err=tcsetattr(fd,TCSAFLUSH,&term);
if(err==-1 && err==EINTR){
perror("Cannot set the attribution of the terminal");
return 1;
}
return 0;
}
int getpasswd(char* passwd, int size)
{
int c;
int n = 0;
printf("Please Input password:");
do{
c=getchar();
if (c != '\n'||c!='\r'){
passwd[n++] = c;
}
}while(c != '\n' && c !='\r' && n < (size - 1));
passwd[n] = '\0';
return n;
}
int main()
{
char *p,passwd[20],name[20];
printf("Please Input name:");
scanf("%s",name);
getchar();
set_disp_mode(STDIN_FILENO,0);
getpasswd(passwd, sizeof(passwd));
p=passwd;
while(*p!='\n')
p++;
*p='\0';
printf("\nYour name is: %s",name);
printf("\nYour passwd is: %s\n", passwd);
printf("Press any key continue ...\n");
set_disp_mode(STDIN_FILENO,1);
getchar();
return 0;
}
for linux
For the sake of completeness: There is no way to do this in C. (That is, standard, plain C without any platform-specific libraries or extensions.)
You did not state why you wanted to do this (or on what platform), so it's hard to make relevant suggestions. You could try a console UI library or a GUI library. You could also try your platform's console libraries. (Windows, Linux)

How to add statement if-else?

How to add if-else statement for "kodeprodi"?
Everytime I add if-else statement, the message "Lvalue required" always appears.
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct {
char bp[13];
char nama[15];
int kodeprodi;
char namaprodi[10];
float ipk;
} mahasiswa;
int main()
{
char pil;
do {
mahasiswa mhs[10];
int i, n;
{
printf("Data Nilai Mahasiswa\n");
printf("Berapa banyak data = ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
printf("Data mahasiswa ke-%d\n", i+1);
printf("Nomor BP: "); scanf("%s", &mhs[i].bp);
printf("Nama: "); scanf("%s", &mhs[i].nama);
printf("Kode Prodi: "); scanf("%d", &mhs[i].kodeprodi);
printf("IPK: "); scanf("%f", &mhs[i].ipk);
if (mhs[i].kodeprodi == 260) {mhs[i].namaprodi = "SI";}
else if (mhs[i].kodeprodi == 261) {mhs[i].namaprodi = "TI";}
}
//output
printf("No. BP Nama Kode Prodi Nama Prodi IPK \n");
for(i = 0; i < n; i++) {
printf("\n%2d %-10s %-9s %3d %3s %3.f\n",
i+1, mhs[i].bp, mhs[i].nama, mhs[i].nama,
mhs[i].kodeprodi, mhs[i].namaprodi, mhs[i].ipk);
}
}
printf("Repeat again? Y/N");
scanf("%s", &pil);
printf("\n\n");
} while ((pil == 'Y') || (pil == 'y'));
}
Even if in the statement if-else, I type like this
if(mhs[i].kodeprodi==260){namaprodi = "SI");
The error message is "Undefined symbol 'namaprodi'
I tweaked your code a bit. Got rid of unused conio.h, changed kodeprodi type to int (because char can only handle numbers -127..127), removed & from some scanf calls (because you should pass pointer to first character for %s formatter), deleted extra mhs[i].nama argument for printf.
Sorry, I completely didn't understood your code :-) My tweaks were semi-automatic! You should learn C programming better.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char bp[13];
char nama[15];
int kodeprodi;
char namaprodi[10];
float ipk;
} mahasiswa;
int main() {
char pil;
do {
mahasiswa mhs[10];
int i, n;
{
printf("Data Nilai Mahasiswa\n");
printf("Berapa banyak data = ");
scanf("%d", &n);
for(i=0;i<n;i++) {
printf("Data mahasiswa ke-%d\n", i+1);
printf("Nomor BP: "); scanf("%s", mhs[i].bp);
printf("Nama: "); scanf("%s", mhs[i].nama);
printf("Kode Prodi: "); scanf("%d", &mhs[i].kodeprodi);
printf("IPK: "); scanf("%f", &mhs[i].ipk);
if(mhs[i].kodeprodi==260)
strcpy(mhs[i].namaprodi, "SI");
else if(mhs[i].kodeprodi==261)
strcpy(mhs[i].namaprodi, "TI");
}
//output
printf("No. BP Nama Kode Prodi Nama Prodi IPK \n");
for(i=0;i<n;i++) {
printf("\n%2d %-10s %-9s %3d %3s %3.f\n", i+1, mhs[i].bp, mhs[i].nama, mhs[i].kodeprodi, mhs[i].namaprodi, mhs[i].ipk);
}
}
printf("Repeat again? Y/N");
scanf("%s", &pil);
printf("\n\n");
} while ((pil == 'Y') || (pil == 'y'));
return 0;
}
For a quick fix, use:
if(mhs[i].kodeprodi==260){strncpy(mhs[i].namaprodi, "SI", 9);
strncpy() is needed to copy the contents into namaprodi.
namaprodi is a member of struct mahasiswa, so you can't access it directly.
But better use std::string instead.
Also, as #BoPersson mentioned, char kodeprodi; can't hold 260, so you'll better to convert that to an int.

X&0 Game IPC FIFO windows [closed]

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 want to make a x&0 game with ipc in c.i declare 3 char arrays,read the witch line to choose and the on what position to put the x or 0.when i try to send line number through the fifo from the client the server recieves a different number.for example i send 1 and the server gets 3144200....this is the code it's not all just one read and write.
this is the server:
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
int main() {
HANDLE f1, f2;
DWORD x;
char l1[3]="\0";
char l2[3]="\0";
char l3[3]="\0";
char X='x';
char* a="";
char* lineChar="";
int n=1,lineInt=0,coor=0;
printf("I am the server \n");
printf("You will play with x\n");
// creating pipes
f1=CreateNamedPipe(TEXT("\\\\.\\PIPE\\fifo1"), PIPE_ACCESS_INBOUND,PIPE_TYPE_BYTE|PIPE_WAIT, 3, 0, 0, 0, NULL);
f2=CreateNamedPipe(TEXT("\\\\.\\PIPE\\fifo2"), PIPE_ACCESS_OUTBOUND,PIPE_TYPE_BYTE|PIPE_WAIT, 3, 0, 0, 0, NULL);
ConnectNamedPipe(f1, NULL);
ConnectNamedPipe(f2, NULL);
while(n<=9){
for(int i=0;i<=2;i++){
printf("[%s]",&l1[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l2[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l3[i]);
}
printf("\n");
printf("You will begin,select the line from 1 to 3 : \n");
scanf_s("%d",&lineInt);
x=0;
lineChar=reinterpret_cast<char*>(lineInt);
printf("%s",lineChar);
//strcpy_s(a,sizeof(lineChar),lineChar);
if (WriteFile(f2,lineChar,sizeof(lineChar)+1, &x, NULL)==0) {
printf("writing error..%d\n", x);
}
n++;
}
DisconnectNamedPipe(f1);
DisconnectNamedPipe(f2);
CloseHandle(f1);
CloseHandle(f2);
}
this is the client :
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
int main(){
HANDLE f1, f2;
DWORD x;
char l1[3]="\0";
char l2[3]="\0";
char l3[3]="\0";
char o='0';
char* lineChar="";
int n=1,lineInt=0,coor=0;
printf("I am the client \n");
printf("You will play with 0\n");
// connect to pipes created by server
f1=CreateFile(TEXT("\\\\.\\PIPE\\fifo1"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
f2=CreateFile(TEXT("\\\\.\\PIPE\\fifo2"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
while(n<=9){
for(int i=0;i<=2;i++){
printf("[%s]",&l1[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l2[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l3[i]);
}
printf("\n");
x=0;
Sleep(3000);
if (ReadFile(f2, lineChar, sizeof(lineChar), &x, NULL)==0) {
printf("reading error..%d\n", x);
}
printf("%s",lineChar);
//lineInt=atoi(lineChar);
//printf("\n%d\n",lineInt);
n++;
}
CloseHandle(f1);
CloseHandle(f2);
}
You have lots or problems with strings and pointers in your code.
To start with you print out the single characters in the arrays as strings, which will cause weird output.
Secondly, and one of the causes of your problem, when you call WriteFile you use sizeof(lineChar) which returns the size of the pointer, not the length of the string. Use strlen instead.
The second cause of your problem is that you cast an integer to a string. This will not work! What the statement
lineChar=reinterpret_cast<char*>(lineInt);
does is that it makes a pointer out of the value in lineInt. This is not a valid pointer! There are a couple of ways to do it:
Use the new std::to_string to convert a value to a std::string.
Since you mix C and C++ anyway, you could use sprintf too.
Your programs have a lot of what is called undefined behavior, and you should be happy that neither of them crashes outright.
#include<stdio.h>
#include<string.h>
int main(){
char l1[3]="\0";
char l2[3]="\0";
char l3[3]="\0";
char x='x';
char o='0';
int n=1,lineInt=0,coor=0,next=1;
printf("X & 0 Game : \n");
while(n<=3){
for(int i=0;i<=2;i++){
printf("[%s]",&l1[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l2[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l3[i]);
}
printf("\n");
switch (next){
case 1 :{
printf("To select the line enter 1,2 or 3 : \n");
scanf_s("%d",&lineInt);
switch (lineInt){
case 1 :{
printf("Enter the coordinates : \n");
scanf_s("%d",&coor);
//printf("%c",x);
//printf("%d",coor);
//strcpy_s(&l1[coor],1,"x");
l1[coor]=x;
break;
}
case 2 :{
printf("Enter the coordinates : \n");
scanf_s("%d",&coor);
l2[coor]=x;
break;
}
case 3 :{
printf("Enter the coordinates : \n");
scanf_s("%d",&coor);
l2[coor]=x;
break;
}
next=2;
}
for(int i=0;i<=2;i++){
printf("[%s]",&l1[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l2[i]);
}
printf("\n");
for(int i=0;i<=2;i++){
printf("[%s]",&l3[i]);
}
printf("\n");
case 2 :{
printf("To select the line enter 1,2 or 3 : \n");
scanf_s("%d",&lineInt);
switch (lineInt){
case 1 :{
printf("Enter the coordinates : \n");
scanf_s("%d",&coor);
l1[coor]=o;
break;
}
case 2 :{
printf("Enter the coordinates : \n");
scanf_s("%d",&coor);
l2[coor]=o;
break;
}
case 3 :{
printf("Enter the coordinates : \n");
scanf_s("%d",&coor);
l2[coor]=o;
break;
}
next=2;
}
}
}
n++;
}
}
}