[英]Reading in an unknown number of integers separated by spaces into one vector per line
[英]Reading a line with integers and a string with spaces
我的輸入格式如下:
整數多字串整數
我知道多字串的最大長度,但我不知道它包含多少字。 我怎么讀呢?
我先讀了這行,然后將第一個和最后一個單詞轉換為整數。 松散:
std::string line;
std::getline(infile, line);
size_t ofs_front = line.find(' ');
size_t ofs_back = line.rfind(' ');
int front = std::strtol(line.substr(0, ofs_front).c_str(), NULL, 0);
int back = std::strtol(line.substr(ofs_back).c_str(), NULL, 0);
std::string text = line.substr(ofs_front, ofs_back - ofs_front);
你必須做一些修改來擺脫空間(例如增加偏移量以吞噬所有空間),你應該添加大量的錯誤檢查。
如果要標准化文本中的所有內部空間,那么還有另一種使用字符串流的解決方案:
std::vector<std::string> tokens;
{
std::istringstream iss(line);
std::string token;
while (iss >> token) tokens.push_back(token);
}
// process tokens.front() and tokens.back() for the integers, as above
std::string text = tokens[1];
for (std::size_t i = 2; i + 1 < tokens.size(); ++i) text += " " + tokens[i];
讀第一個整數。 跳轉到字符串后面並跳過數字。 然后從這一點讀取一個int。 中間的部分是字符串。 可能不是100%正確但是:
char buf[256], *t = buf, *p, str[256];
fread(buf, 1, 256, file);
int s,e;
t += sscanf(buf, "%d", &s);
*p = buf + strlen(buf);
while (isdigit(*p)) p--;
sscanf(p, "%d", &e);
strncpy(str, p, p - t);
這不如@ KerrekSB的解決方案那么有效,但另一種方法是提取第一個整數,然后循環遍歷字符串的其余部分,直到找到第二個整數。
#include <iostream>
#include <sstream>
int main()
{
std::istringstream ss( "100 4 words to discard 200" );
int first, second;
char buf[1000] = {0};
if( !( ss >> first ) ) {
std::cout << "failed to read first int\n";
return 1;
}
while( !( ss >> second ) || !ss.eof() ) {
if( ss.eof() ) {
std::cout << "failed to read second int\n";
return 1;
}
ss.clear();
if( ss.getline( buf, 1000, ' ' ).bad() ) {
std::cout << "error extracting word\n";
return 1;
}
}
std::cout << "first = " << first << "\n";
std::cout << "second = " << second << "\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.