User input in D - io

I am somewhat new to D, and I am trying to receive user input, like this, with a prompt:
string str;
writeln("Enter a string: ");
str = readln;
writeln(str);
However, the prompt appears after I enter the input; any reason why?
I've trawled the internet for a good hour, but I can't seem to find an answer.

Your code is correct, it's your terminal or whatever you use to see your program's output that doesn't flush stdout. You can force it though:
string str;
writeln("Enter a string: ");
stdout.flush;
str = readln;
write(str);

Related

I used cin to get a string input as shown below in the code and it works fine. Is it alright?

#include<iostream>
#include<stdio>
using namespace std;
int main()
{ int n;
char s[15];
cin>>n;
cin>>s;
cout<<n*2<<"\n";
cout<<s;
return 0;
}
I tried with gets and fgets function but they don't work just after cin..
I'm kind of confused on what you are asking here, but I have noticed something here that can be fixed.
Yes the code you have compiles and it works. However, it could be improved.
When prompted to input something to your char array, you'll notice that it will not accept whitespaces. So if I input, Jon Smith, the output will only be Jon and the rest of the string input is cut off. To fix this, you will need to make a call the the getline() function.
The documentation of getline() states:
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n'..)
This will allow you to get whitespaces from the input and put the entire input back into a string.
If you add this function call to your code where the second input prompt lies and you were to run the code, you would notice that you will only get prompted once and then the program would finish running before the second prompt appears to be executed. This is because getline() does not ignore leading whitespace characters and it stops reading any further because the cin>> before it is seen as a newline character.
To make getline() work with cin>>, you must use cin.ignore() before the call to getline(). Below is some code that I wrote to make this adjustment:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string s; //using string allows us to use getline()
cout<<"Enter a number: "; //Let user know they are being prompt for number
cin>>n;
cin.ignore(); //ignore the leading newline
cout<<"Enter a string: "; //let user know being prompt for string
getline (cin,s);
cout<<n*2<<"\n";
cout<<s;
return 0;
}
Again, the code you have works and compiles. I'm not sure if my solution is the answer you are hoping to get but I hope that you are able to find this useful! Cheers!

run an EXE file and receive return value from it using VC++

Please i want to creat a program/function in VC++ that allow me to run an EXE file and receive return value from it.
My EXE file tht i want to run is a console Application, it need two argument Arg1 (String) and Arg2 (Float), and return an OutPut (Float).
Something like :
OutPut = MyEXEFile.exe Arg1 Arg2
Command-line arguments come in only one data type: array of C-style string.
Input and output come in only one data type: stream of bytes.
You can supply any command-line and redirection the output if you use CreateProcess from the <windows.h> header file. Other data types such as float will need to be handled the same way you would handle them in a data file.
Here is an example on MSDN: Creating a Child Process with Redirected Input and Output
I find the solution, this is work fine for me, i test it, and it work well.
This is the link of the page where i find the solution, i fixe some errors, and now it ready for implement.
http://www.codeproject.com/Articles/10134/Execute-a-Console-Application-From-VC?fid=172409&fr=26#xx0xx
This is the exemple we need to execute. PS: this line is not a part of the our program, it's just here to explain the algorithm:
MyEXEFile.exe Arg1 Arg2 > sResult
The "MyEXEFile.exe" take two arguments (Arg1 and Arg2) and return a value in the sResult Variable.
Let us program this exemple with Visual C++ using CreatProcess :
CString ExePath="C:\\MyEXEFile.exe";
CString arg1="2";
CString arg2="3";
CString sResult="";
CString strCommandLine = ExePath + " " + arg1 + " " + arg2;
// Call the ExecuteExternalFile function
sResult = ExecuteExternalFile(strCommandLine);
This is the Function who will read the output of MyEXEFile.exe File :
CString ExecuteExternalFile(CString csExecute)
{
SECURITY_ATTRIBUTES secattr;
ZeroMemory(&secattr,sizeof(secattr));
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = TRUE;
HANDLE rPipe, wPipe;
//Create pipes to write and read data
CreatePipe(&rPipe,&wPipe,&secattr,0);
//
STARTUPINFO sInfo;
ZeroMemory(&sInfo,sizeof(sInfo));
PROCESS_INFORMATION pInfo;
ZeroMemory(&pInfo,sizeof(pInfo));
sInfo.cb=sizeof(sInfo);
sInfo.dwFlags=STARTF_USESTDHANDLES;
sInfo.hStdInput=NULL;
sInfo.hStdOutput=wPipe;
sInfo.hStdError=wPipe;
char command[1024];
strcpy(command,csExecute.GetBuffer(csExecute.GetLength()));
//Create the process here.
CreateProcess(0,command,0,0,TRUE,NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
CloseHandle(wPipe);
//now read the output pipe here.
char buf[100];
DWORD reDword;
CString m_csOutput,csTemp;
BOOL res;
do
{
res=::ReadFile(rPipe,buf,100,&reDword,0);
csTemp=buf;
m_csOutput+=csTemp.Left(reDword);
}while(res);
CloseHandle( pInfo.hProcess );
CloseHandle( pInfo.hThread );
return m_csOutput;
}
Creating a Child Process with Redirected Input and Output
You are going overkill.
For a command line app, the system command will do what you are looking for.
int status = system("MyEXEFile.exe Arg1 Arg2");

how to take int or double type input in C# in console?

how to take input of int or double type in C# in console???
i had taken input in C++ and C .But in C# ,i am not able to give user input at the run time. So tell how to take input at the run time in C#.
Try this -
double a;
int b;
a = Convert.ToDouble(Console.ReadLine()); // Value in double
b = Convert.ToInt32(Console.ReadLine()); // Value in Int
You need to read a line of textual input using Console.ReadLine(), then parse it as a number using int.Parse() or double.TryParse() or other variants.
Use Console.ReadLine to read input as string and then convert them to your required type, using int.Parse or int.TryParse, or double.Parse, or double.TryParse like:
string input = Console.ReadLine();
int temp;
if (int.TryParse(input, out temp))
{
//valid int input
}
else
{
//invalid int input
}
Console.WriteLine(temp); //input number
Its better if you use TryParse family of methods for parsing, since they will not raise an exception in case of failed parsing.
You may also see: How to: Convert a String to a Number (C# Programming Guide)
Use Console.ReadLine() that lets you to put an input and you can assign it to the input you wish, if int then parse it.
Try using
Console.ReadLine();
ex:
Console.Writeline("1. Do Something");
string input = Console.ReadLine();

Read a String with spaces till a new line in C

I am in a pickle right now. I'm having trouble taking in an input of example
1994 The Shawshank Redemption
1994 Pulp Fiction
2008 The Dark Knight
1957 12 Angry Men
I first take in the number into an integer, then I need to take in the name of the Movie into a string using a character array, however i have not been able to get this done.
here is the code atm
while(scanf("%d", &myear) != EOF)
{
i = 0;
while(scanf("%[^\n]", &ch))
{
title[i] = ch;
i++;
}
addNode(makeData(title,myear));
}
The title array is arbitrarily large and the function is to add the data as a node to a linked list. right now the output I keep getting for each node is as follows
" hank Redemption"
" ion"
" Knight"
" Men"
Yes, it oddly prints a space in front of the cut-off title. I checked the variables and it adds the space in the data. (I am not printing the year as that is taken in correctly)
How can I fix this?
You are using the wrong type of argument passed to scanf() -- instead of scanning a character, try scanning to the string buffer immediately. %[^\n] scans an entire string up to (but not including) the newline. It does not scan only one character.
(Marginal secondary problem: I don't know from where you people are getting the idea that scanf() returns EOF at end of input, but it doesn't - you'd be better off reading the documentation instead of making incorrect assumptions.)
I hope you see now: scanf() is hard to get right. It's evil. Why not input the whole line at once then parse it using sane functions?
char buf[LINE_MAX];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int year = strtol(buf, NULL, 0);
const char *p = strchr(buf, ' ');
if (p != NULL) {
char name[LINE_MAX];
strcpy(name, p + 1); // safe because strlen(p) <= sizeof(name)
}
}

From Real into String Variable Conversation

Please help, how can i convert a real declared variable into a string one. Is there any function like IntToStr() ? RealToStr() function won't work.
There is a bunch of conversion routines in SysUtils unit, ie FloatToStr and other FloatTo* functions. Also see the Format function.
A really old method uses the 'Str' procedure, which has two parameters: the first is a real or integer, and the second is a string variable, into which the formatted number will be placed.
Examples:
i:= 1;
str (i, a); // a = '1'
r:= 1.5;
str (r:2, a); // a = '1.50'
It depends on the Delphi version you are using.
There is a FloatToStr in newer versions.
I think something like this would work...
procedure TestConversion;
Var
StringValue : String;
RealValue : Real;
begin
RealValue := 1 + 1.95;
Str(RealValue:0:2,StringValue);
// to display it in a label for example, it should be like this:
Label1.Caption := StringValue + ' is a Real Value!';
end;
so the output should be displayed in the Label1.Caption(as example) without problems like this:
2.95 is a Real value!

Resources