Program segment works ok but is skipping the first task in the if statement.
The output is as follows if user has selected "Y"
Do you wish to add another subject code - Y or N?
y
Enter the subject name:
Enter subject code:
abc123
It is not giving the user the chance to enter the subject name. It worked before creating the if statement, so I am assuming it has something to do with that. I have been wracking my brain but to no avail.
System.out.println("Do you wish to add another subject code - Y or N? ");
String response = input.next();
if (response.equalsIgnoreCase("Y")) {
/**User input*/
System.out.println("\nEnter the subject name: ");
String subjectName = input.nextLine();
System.out.println("\nEnter subject code: ");
String subjectCode = input.next();
Subject mySubject = new Subject(subjectCode, subjectName);
/**Write to the file*/
output.println(mySubject.getSubjectCode() + " " + mySubject.getSubjectName());
output.close();
}
else
output.close();
System.out.println("\nProgram terminated\n");
Cheers,
Susan
String response = input.next(); // Wrong
String response = input.nextLine(); // Right
When you do input.next(), you just read the first word of the line.
When you afterwards do input.nextLine(), you read up until the next line feed.
That means that if you type y<enter>, the first statement will read y and the second statement will read up until the <enter> which is just the empty string.
Related
I have tried the Function below ,
string checkstring(int sublen){
bool quit = false;
string temp;
while(!quit){
cin>>temp;
if (temp.size()> sublen){
cout<<"\t"<<"Error , Only "<<sublen<<"characters are allowed "<<endl;
cin.clear();
getch();
}else{
return temp;
quit=true;
}
}
}
The Problem is , if i enter any digit in the input string , it skips few lines.
Ex :-
Enter Your Last Name : Mayer 23,
it Skips next question from the loop
Question Marked with blue has skipped - Please view thus image | Cursor at Red Mark
Sorry About my bad English ! Please Help!
When you read text using the >> operator, it separates on white-space. If you want a whole line use std::getline instead.
so this user input all in one line string , i need to parse the input into two categories: user age and user name.
for example , the user input -->> [23:Frank] [15:Jack] [45:] [33:sofia] []
in this case i have more than one argument (delimiter, total of 3 ) which are [:] , in addition i need to get user input and stop looping once i encounter the [] at the end.
this is what i was thinking :
string input;
vector<string> age;
vector<string> name;
cin >> input;
while (input != "[]")
{
get age between first [ and :
assign to age variable
get name between : ]
assign to user name variable
................
}
also - what if one of the brackets is missing a name , how can assign a blank name and skip that part in order to process the rest (meaning i will output age with no name next to it).
any suggestions regarding how to get and process the data.
i saw some advance stuff like Toknizing and booster which are advance for my course, that's why i was thinking about straight forward getline and parse functions.
Thank you.
Read in token like you are currently doing with cin
test for [] as you are doing with the while loop
For the inside the loop, here are a few things to help you out:
std::string's front and back functions are perfect for ensuring that input starts with [ and ends with ]
std::string's substr function is perfect for trimming off the [] so you can easily ignore them for the rest of the parsing
std::stringstream allows you to call make a stream that only contains your trimmed input.
std::getline(stream, string, char) will read all characters it finds up to the char parameter or the end of the stream and stuff the results in the string parameter and then discard the char it found so you won't trip over it parsing the rest of the input.
strtoul will convert a string into a number and tell you if it failed. It will not accept negative numbers so you can catch people trying to trick your program.
getline(stream, string) will read the stream until it hits an end of line marker. Perfect for reading the rest of a stream that contains no end of lines.
Using strtoul:
char * endp;
unsigned long agenum strtoul(agestr.c_str(), // turn string into old c-style string
&endp, // will be updated with the end of the char after the last number
10); // base ten numbers
if (endp != '\0') // old c-strings always end on a null (numerical zero). If strtoul
// didn't end on a null, the string wasn't a valid number.
{
//not a number
}
Ok , so THANKS for people who helped or at least tried to help!!
what i end up doing for this part was as follows:
read in each string at once
use the find function in order to locate my delimiters ( which are in this case [ : ] )
return positions per each perimeter based on my argument (each pair will hold either the beginning and the end for age || name)
pass those arguments results to truncate the string by using substr function, then assign into each variables.
while (true)
{
string myInput;
cin >> myInput;
while (myInput != "[]")
{
int age_beg = myInput.find('[') + 1 ;
int age_end = myInput.find(':', age_beg);
string age = myInput.substr(age_beg, (age_end - age_beg));
int name_beg = age_end + 1;
int name_end = myInput.find(']', name_beg);
string name = myInput.substr(name_beg, (name_end - name_beg));
cout << "NAME : " << name << " AGE : " << age << endl;
cin >> myInput;
}
}
Hope this will help others with the same question in the future !!
I'm trying to create code in Java where the user creates (inputs) a phrase, and then picks (inputs) a character.
From there I'm suppose to take the users input and replace the character they picked in to X in the phrase they created. I'm not entirely sure how to create this, I know I'm suppose to use Scanner and then I don't know if I have to create a new string or use a mutation method. It's suppose to look like this when run:
Enter phrase: Pizza is good
Enter Character: z
Pixxa is good
I am fairly new to Java and this is what I have tried so far
Here's my code:
import java.util.Scanner;
public class ModifyStrings
{
public static void main (String[] args)
{
String enterPhrase;
String enterCharacter;
//Scanner
Scanner scan2 = new Scanner (System.in);
//Print out that the user will see and type in
System.out.println("Enter a phrase or sentence: ");
enterPhrase = scan.nextLine();
//Second print out that the user will enter in for a character to change
System.out.println("Enter Character: ");
enterCharacter = scan.nextLine();
//mutation
?
//Character changes that letter into x
System.out.println("New phrase: "+ enterPhrase);
}
}
Thank you!
this is simply can be done by using String method replaceAll(). try the code below this will work for you.
import java.util.Scanner;
public class ModifyStrings {
public static void main (String[] args) {
String enterPhrase;
String enterCharacter;
//Scanner
Scanner scan = new Scanner (System.in);
//Print out that the user will see and type in
System.out.println("Enter a phrase or sentence: ");
enterPhrase = scan.nextLine();
//Second print out that the user will enter in for a character to change
System.out.println("Enter Character: ");
// This line of code firstly get the string truncate white spaces and then get the first character not all
enterCharacter = scan.nextLine().trim().substring(0, 1);
//Mutation code replace x with your desired character do you want to replaces
enterPhrase = enterPhrase.replaceAll(enterCharacter, "x");
//Character changes that letter into x
System.out.println("New phrase: "+ enterPhrase);
}
}
I am trying to allow the user to either enter a string or just hit enter, and in that case I would use a default string.
cout << "Where should I save the exam (default (./)exam.txt): " ;
cin >> exam_filename;
But right now you can enter a string and it works fine, but if you hit enter it just keeps waiting for the user to type something. Any suggestions??
Okay so when I do this:
string exam_filename;
getline(cin, exam_filename);
if (exam_filename.empty())
// set to default string
now it always sets the string to the default string. It never gives me a chance to enter anything it just moves on the next part of the program autmoatically.
You really want to read a line. Just do it:
string exam_filename;
getline(cin, exam_filename);
if (exam_filename.empty())
// set to default string
In C++, Ubunt 12.04, I have a file named config.txt which contains user name and password. I have 2 public static string variables: USER and PASSWORD. This is my code:
// Read file from config
string text[2];
int count = 0;
while(!fin.eof()){
getline(fin,text[count]);
count++;
if(count == 2){
break;
}
}
CONNECTOR::USER = text[0];
CONNECTOR::PASSWORD = text[1];
string userAndPassword = CONNECTOR::USER + ":" + CONNECTOR::PASSWORD;
cout << CONNECTOR::USER << endl; // It's fine, right user: qsleader
cout << CONNECTOR::PASSWORD << endl; // ok, right password: 123456
cout <<"user and password: " << userAndPassword << endl; // It's weird text! Problem here!
The weird text result is: :123456d password: qsleader!! This is not what I expected! But I don't know why this happen? Can anyone give me an suggestion? (If i print: cout << "user and password: qsleader:123456", the result is good!!)!
The problem is created when you read the values. Indeed, I guess that your file has the two items on two different lines. Furthermore, I guess this file uses Windows line endings. Therefore, when you read the first item, it reads qsleader\r and then stops as the next extracted character is \n, extracted but not appended to the string.
When you create the userAndPassword string, it is in fact qsleader\r:123456. This special character \r is a return carriage. It makes the cursor go to the beginning of the line. Therefore, on the last line, you first output user and password: qsleader, then go back to the first column, and write :123456, resulting in :123456d password: qsleader.
You are setting userAndPassword to a hellish expression involving assignments. I guess your intent was:
string userAndPassword = CONNECTOR::USER + ":" + CONNECTOR::PASSWORD