我有一个txt文件。这是索引:
1 A D C V K O F R W
2 Y I J M
3 Q P
4 E S Z N L
我在名为string readen[9];
的变量中得到了字母
readen[0]` = "A D C V K O F R W";
readen[1]` = "Y I J M";
像这样,它们之间有空白。我需要一个接一个地抓住所有字母:
readen[0]` = "A";
readen[1]` = "W";
(无空白)
这是我的代码:
string read;
string readen[9];
char numbers[9];
ifstream file;
file.open("deneme.txt", ios::in);
for (int i = 0; !file.eof(); i++)
{
numbers[i] = file.get();
file.get();
getline(file,read);
readen[i] = read;
}
就像我说的,现在就这样-> readen[0]
=“ A D C V K O F R W”
保持readen[0] = 'A' readen[1] = 'D'
这样的最佳方式是什么?
答案 0 :(得分:0)
#include <cctype> // std::isalpha()
#include <vector>
#include <iostream>
#include <fstream>
int main()
{
std::ifstream is{ "deneme.txt" };
std::vector<int> numbers;
std::vector<char> letters;
for (;;) {
int number;
int ch;
// as long as extraction of an integer fails extract characters
while (!(is >> number) && (is.clear(), (ch = is.get()) != EOF)) {
if(std::isalpha(static_cast<unsigned>(ch)))
letters.push_back(ch);
}
if (!is) break;
numbers.push_back(number);
}
std::cout << "Numbers: ";
for (auto const &n : numbers)
std::cout << n << ' ';
std::cout << "\nLetters: ";
for (auto const &l : letters)
std::cout << l << ' ';
std::cout.put('\n');
}
Numbers: 1 2 3 4
Letters: A D C V K O F R W Y I J M Q P E S Z N L
答案 1 :(得分:0)
我解决了。我陷入了循环。每次letters[x] = file.get(); file.get();
都会先输入字母,然后忽略1个空白字符。