Assigning variables while ignoring symbols? (c++) [duplicate] - c++

This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 9 years ago.
I was wondering how you would assign multiple variables from a single line of user input if it contained symbols. Such as, if the user input was 5-25-1995, is it possible to assign 5, 25, and 1995 to different variables and ignore the "-"'s? I have been trying to use cin.ignore(), but haven't had any luck as of yet.
Thanks.
Short version:
user inputs "3-24-1995"
desired outcome
int month is 3,
int day is 24,
int year is 25,

char dummy;
int month, day, year;
cin >> month >> dummy >> day >> dummy >> year;

As your specific requirement was that the input be in the form "3-24-1995", therefore
may be something along the lines will comply with your needs and produce what you wanted.
/* Code */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char str[] ="3-24-1995"; // Your input that you will have some way of getting
char * month, *day, *year;
month=strtok (str,"-");
day = strtok (NULL,"-");
year = strtok (NULL,"-");
// Here, converting to int, just because you were looking to convert it into
// int otherwise you could just leave it un converted too.
printf("month: %d day: %d year: %d\n",atoi(month), atoi(day), atoi(year));
}

Related

im trying to display the full name like the output did , but whenever i hit enter the program just print out 1 word rather than 2 word

question
3. Reads full name and year of birth, then show the full name and age
Input: anonymous anonymous 2000
Output: Hello anonymous anonymous, this year you are 19 years old
can somebody help me how to display a full name in my code, and im very new about this programming thing
(the input and output has to be the same as the question)
#include <stdio.h>
int main()
{
char name[25];
int birth;
int age;
scanf("%s %d",&name,&birth);
age = 2019 - birth;
printf("Hello %s, this year you are %d years old",name,age);
return 0;
}
scanf splits up the input string by whitespace characters. Therefore, the first anonymous will be put into the first %s token, but the second one won't. Without overcomplicating things and keeping scanf (which is mostly frowned upon due to buffer overflow issues etc), the quickest thing to do would be to have two buffers, one for first name, one for last name.
#include <stdio.h>
int main()
{
char firstName[25];
char lastName[25];
int birth;
int age;
scanf("%s %s %d",&firstName,&lastName,&birth);
age = 2019 - birth;
printf("Hello %s %s, this year you are %d years old",firstName,lastName,age);
return 0;
}

Char seperated by a decimal into a double c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am passing a string variable (std::string) and iterating through the string character by character. Whenever I run into a decimal, I want to combine the previous position on the string (i.e 2) and the next position in the string (i.e 5) into a double. So how would I go about making the char 2, char . , char 5 into one whole value (2.5)?
std::double x;
std::string varibleName = "4 5 7 2.5";
for (int i = 0; i < variableName.length(); i++) // iterates through variableName
{
if (variableName[i] == '.'){ // if the current position of the iteration is a decimal, I want to grab the char before the decimal and the char after the decimal so I can combine all three positions of the string making it 2.5 and not 25.
}
}
Well, you are wildly overthinking it. The C++ library provides std::stof, std::stod, std::stold that does exactly what you want. Convert a string like "2.5" to a float, double or long double, e.g.
#include <iostream>
int main (void) {
std::string s = "2.5";
double d = std::stod(s);
std::cout << d << "\n";
}
Example Use/Output
$ ./bin/stodex
2.5
Look things over and let me know if you have further overthinking questions.
Note that giving an example, code snips, and error logs make troubleshooting a lot easier :)
It sound like you have some input like "2.1" and need to convert it to a double like 2.1?
If that is the case you can use the <cstdlib> atof function.
Example:
/* atof example: sine calculator */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atof */
#include <math.h> /* sin */
int main ()
{
double n;
char buffer[256];
printf ("Enter degrees: ");
fgets (buffer,256,stdin);
n = atof (buffer);
printf ("You entered %s which is a double like %f\n" , buffer, n);
return 0;
}

c++ getline putting different parts of a line into variables [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 5 years ago.
For the life of me, I can't seem to figure out how to do this properly.
First, I read a line from a csv file. Lets say, that line has
2992854,BOB,3452,394832
I don't want to read each result into a console like practically every example I've found, I want them to go in order, into these 4 variables:
int time;
string name;
int location;
int point;
Right now, this is my code:
string line;
ifstream inputFile("input.csv");
std::list<Cramista> Cramistas;
while (!inputFile.eof())
{
int time;
string name;
int location;
int point;
std::vector<std::string> stringArray;
std::size_t position = 0, found;
getline(inputFile, line);
while ((found = line.find_first_of(',', position)) != std::string::npos)
{
stringArray.push_back(line.substr(position, found - position));
position = found + 1;
}
time = stoi(stringArray[0]);
name = stringArray[1];
location = stoi(stringArray[2]);
point = stoi(stringArray[3]);
}
UPDATED:
So, with what I have here, I'm able to get the first 3 out of 4 pieces of the line, and put them into an array, which I can then move into variables. Trying to figure out how to get that 4th part.
I've got 2992854, BOB, and 3452 but I don't have 394832.
I mean basically in order to avoid "reading each result into the console" using
cin >> time >> name >> location >> point;
you would have to split the line by commas (assuming it's a string, then convert the non string data to integers.

c++ How to convert String to int (ascii code to value); [duplicate]

This question already has answers here:
How to convert a single char into an int [duplicate]
(11 answers)
Closed 5 years ago.
i have been trying to make a program that checks if a national identification number is valid how ever i have run into a issue and i can't find an answer anywhere.
I am using a string to store the users input of the identification code and i need to somehow covert the string to int keeping the symbol instead of getting an ascii value.
Example:
(lets say the user inputs the string persKods as 111199-11111
the 5th symbol is 9 so the year value should output as 9 instead of 54 which is its ascii value)
int day,month,year;
year=this->persKods.at(4);
cout << year; // it outputs 54 instead of 9 :/
Can you try to ascci value of '0'.
#include <iostream>
using namespace std;
int main() {
// your code goes here
string str="111199";
int test = str.at(4) - '0';
cout<<test;
return 0;
}
For more information link

How to incorporate a large list of numbers into a c++ code [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 have four lists each containing 84 different rates which I want to be able to access using if/else statements based on the inputted information and I was hoping there was something more efficient than typing each one into an array.
What would be the easiest way to do this? Any hints would be very helpful I just need a starting point.
#include "MaleNonSmoker.txt"
using namespace std;
double ratesmn[85] = {
#include "MaleNonSmoker.txt"
- 1
};
#include <iostream>
#include <string>
#define STARTAGE 15
int main() {
double const *rates;
rates = ratesmn;
int age;
cout << "How old are you?\n";
cin >> age;
double myrate = ratesmn[age - STARTAGE];
return 0;
}
The errors that I am getting are from line 1: syntax error: 'constant'
and from line 7: 'too many initializers'
If the numbers do not change, there is no real need to read the numbers at runtime from a file. You can also use them at compile time.
Create four files with the arrays with any tool you like, but a comma after each number so it looks like this:
51,
52,
53,
In your c++ code, define 4 arrays, and use #include to include the numbers from the text file;
int ratesms[85] = {
#include "ratesms.txt"
-1 // add another number because the txt file ends with a comma
};
Do the same for the other arrays.
In your code determine which list you want to use, and set a pointer to that list, for example
int const *rates;
if ( /* smoking male */ )
rates = ratesms;
else if ( /* other variations */ )
rates = ...
And then use it like this;
#define STARTAGE 15
int age=35; // example
int myrate=rates[age-STARTAGE];
If you don't want to substract the start age from the array index, you can also add 15 dummy numbers to the array;
int ratesms[100] = {
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
#include "ratesms.txt"
-1 // add another number because the txt file ends with a comma
};
now ratesms[15] will contain the first number from the txt file.
You can define an array of numbers in C++ like this:
int[6] rates = {1, 2, 3, 4, 5, 6};
What's the format of your "lists?"
Reading them in should be very simple -- check out this tutorial on file I/O in C++. If you save your lists as simple .txt files, you can read each list item line by line by creating an ifstream and calling getline(). The file data will be read as strings, so you can use stoi() and stod() to convert them to integers and doubles, respectively (check out the string reference for more conversion methods).
You also might want to look into saving your excel files as comma-separated-value (.csv) files, which can then be read in line by line in the same manner. Each line will represent a row with cell values separated by commas, which are very easy to parse.