I have to write a function that will read input from a file. The file is set up: one character, space, word, space, throughout the file, like such:
A space 1 space 2 space... etc
I need to extract the whitespace following the one character and NOT the whitespace following the word.
How can I go about doing this? Should I just make it so the function writes the whitespace itself instead of extracting it?
Also, I am importing this info into a 2-d char array. Will I run into problems trying to write integers to a char array?
Something like this maybe?
#include <iostream>
#include <fstream>
int main() {
char myChar;
char theWS;
std::string word;
std::ifstream in("example.txt");
while(in >> myChar >> std::noskipws >> theWS >> word >> std::skipws) {
std::cout << myChar << theWS << word << '\n';
}
}
You should've been exposed to the idea of a tokenizer by now. This is the structure you need.
You will be fine writing integers into character arrays. Since C and C++ represent ascii characters as small numbers anyways, handling them is easy. Some examples of the number values which correspond to specific chars: '0' => 48, '1' => 49, ... , 'A' => 65, 'B' => 66, etc.
Take a look at http://www.asciitable.com/ for the full set of ascii characters and their corresponding values.
This also allows you to perform mathematical operations on characters such as 'A' + 1 => 'B'
as well as convert between numbers and characters (char) 65 => 'A'
Related
I'd like to count number 1 in my input, for example,111 (1+1+1) must return 3and
101must return 2 (1+1)
To achieve this,I developed sample code as follows.
#include <iostream>
using namespace std;
int main(){
string S;
cout<<"input number";
cin>>S;
cout<<"S[0]:"<<S[0]<<endl;
cout<<"S[1]:"<<S[1]<<endl;
cout<<"S[2]:"<<S[2]<<endl;
int T = (int) (S[0]+S[1]+S[2]);
cout<<"T:"<<T<<endl;
return 0;
}
But when I execute this code I input 111 for example and my expected return is 3 but it returned 147.
[ec2-user#ip-10-0-1-187 atcoder]$ ./a.out
input number
111
S[0]:1
S[1]:1
S[2]:1
T:147
What is the wrong point of that ? I am totally novice, so that if someone has opinion,please let me know. Thanks
It's because S[0] is a char. You are adding the character values of these digits, rather than the numerical value. In ASCII, numerical digits start at value 48. In other words, each of your 3 values are exactly 48 too big.
So instead of doing 1+1+1, you're doing 49+49+49.
The simplest way to convert from character value to digit is to subtract 48, which is the value of 0.
e.g, S[0] - '0'.
Since your goal is to count the occurrences of a character, it makes no sense to sum the characters together. I recommend this:
std::cout << std::ranges::count(S, '1');
To explain the output that you get, characters are integers whose values represent various symbols (and non-printable control characters). The value that represents the symbol '1' is not 1. '1'+'1'+'1' is not '3'.
I am trying to extract numbers from a string.
I would like to save each number to a separate double variable.
I currently tried using a simple stringstream like this.
std::string line = "100.2456426246\200.2624362436\300.136213477347";
std::stringstream stream(line);
stream.precision(20);
double a,b,c;
stream >> a >> b >> c;
Not only is the precision wrong(only prints out 6 digits), it only extracts the first number a(100.245), and b and c is null. I suspect it is due to backslash, but I'm not exactly sure.
What is the best way to read the string which contains backslash between each number and store the whole number with correct precision?
You could use getline with a delimiter to split a string into a vector of elements and atof to extract floats along these lines
vector<string> elems;
stringstream stream(line);
string item;
while (getline(stream, item, "\\")) {
elems.push_back(item);
}
vector<float> val(elems.size());
...
val[i]=atof(elems[i].c_str())
Precision here is more of a matter of presentation, which you can customize with the help of setprecision. For example,
#include <iomanip>
...
cerr << setprecision(6) << val[i] << endl;
will output the truncation to six significant digits.
Another matter is making sure that all digits up to the last one are stored. To make sure that all digits are stored, simply the size of your defined float must be sufficiently large to contain your data, and atof may need to be replaced by an appropriate parser if float should be replaced by double or something else.
First of all, i would like to read from plain text, i read hundreds of webpages about it and i just can't make it. I want to read every byte of the file and every two byte is a number what i want to store.
I want to read: 10 20.
I get: ASCII code of 1, ASCII code of 0, ASCII code of space etc. etc.
I tried several things, like stream.get, or stream.read, tried to convert with atoi but then i can't concatenate the two digits, i tried sprintf but all of them failed.
Array of ASCII codes:
char ASCII[] = "10 20";
Convert to integer variables:
std::istringstream iss(ASCII);
int x,y;
iss >> x >> y;
Done.
Here's the working sample: http://ideone.com/y8ZRGs
If you want to do this with your own code, there are only two things you need to be able to do.
First, you need to convert from the ASCII code of a digit to the number it represents. This is as simple as subtracting '0'.
Second, you need to convert from the numerical value of each digit of a two digit number to the number that represents. This is simple -- if T is the tens place and U is the units, it's 10T + U.
So, for example:
int twoDigitNumber (char tens, char units)
{
return 10 * (tens - '0') + (units - '0');
}
So, I've looked up how to do conversion from text to hexadecimal according to ASCII, and I have a working solution (proposed on here). My problem is that I don't understand why it works. Here's my code:
#include <string>
#include <iostream>
int main()
{
std::string str1 = "0123456789ABCDEF";
std::string output[2];
std::string input;
std::getline(std::cin, input);
output[0] = str1[input[0] & 15];
output[1] = str1[input[0] >> 4];
std::cout << output[1] << output[0] << std::endl;
}
Which is all well and good - it returns the hexadecimal value for single characters, however, what I don't understand is this:
input[0] & 15
input[0] >> 4
How can you perform bitwise operations on a character from a string? And why does it oh-so-nicely return the exact values we're after?
Thanks for any help! :)
In C++ a character is 8 bits long.
If you '&' it with 15 (binary 1111), then the least significant 4 bits are outputted to the first digit.
When you apply right shift by 4, then it is equivalent of dividing the character value by 16. This gives you the most significant 4 bits for second digit.
Once the above digit values are calculated, the required character is picked up from the constant string str1 having all the characters in their respective positions.
"Characters in a string" are not characters (individual strings of one character only). In some programming languages they are. In Javascript, for example,
var string = "testing 1,2,3";
var character = string[0];
returns "t".
In C and C++, however, 'strings' are arrays of 8-bit characters; each element of the array is an 8-bit number from 0..255.
Characters are just integers. In ASCII the character '0' is the integer 48. C++ makes this conversion implicitly in many contexts, including the one in your code.
I just want to write a simple text file:
ofstream test;
test.clear();
test.open("test.txt",ios::out);
float var = 132.26;
BYTE var2[2];
var2[0] = 45;
var2[1] = 55;
test << var << (BYTE)var2[0] << (BYTE)var2[1];
test.close();
But in the output file I get:
132.26-7
I don't get what the problem is...
I think that the problem might be that BYTE type might be a typedef for char. If this were the case, then whenevernyou try to write out a BYTE to a stream, it will print the ASCII character corresponding to that byte rather than the numeric value of the byte. Notice that the characters - and 7 correspond to ASCII values 45 and 55, for example.
To fix this, you'll want to do two things:
Typecast the BYTEs you're writing to some integral type like int or short before writing them to the file. This forces the stream to write a numeric value rather than a character.
Output some amount of whitespace in-between all of the data you output. Right now everythingnis bleeding together because there are no spaces, which makes things harder to read.
Hope this helps!
BYTE is nothing but an alias for unsigned char. By default, when you output a char in a stream, it is converted to its ASCII character. In the ASCII table, the character 45 is '-' and the character 55 is '7'.
Try this instead:
test << var << (int)var2[0] << (int)var2[1];