使用文件提取操作符读取int或string
Read whether int or string using the file extraction operator
我正在从文件中读取,我正在使用提取操作符来获取第一个值。问题是我需要知道这个值是int还是string,这样我就可以把它放在合适的变量中。
我的问题是,我能不能把它放进int型如果失败,它会把它扔进字符串?或者事先检查它是整型还是字符串?
如果需要,我可以提供code/psudocode。
文件的例子:
3 rows 3 columns all @ go
5 columns 6 rows go
5 rows triangular go
alphabetical 3 rows 3 columns go
all ! 4 rows 4 columns outer go
alphabetical triangular outer 5 rows go
有很多方法可以做到这一点,一种方法是简单地将其作为字符串读取,然后尝试在自己的代码中将其解析为整数。如果解析成功,则得到一个整数,否则得到一个字符串。
有几种方法可以解析字符串,包括(但不限于):- 使用
std::istringstream
和>>
操作符,并检查流标志 -
std::stoi
- 程序检查是否所有字符都是数字,使用正常的十进制算术转换。
使用std::stoi
的简单示例:
std::string input;
if (std::getline(std::cin, input))
{
try
{
std::size_t pos;
int n = std::stoi(input, &pos);
// Input begins with a number, but may contain other data as well
if (pos < input.length())
{
// Not all input was a number, contains some non-digit
// characters as position `pos`
}
else
{
// Input was a number
}
}
catch (std::invalid_argument&)
{
// Input is not a number, treat it as a string
}
catch (std::out_of_range&)
{
// Input is a number, but it's to big and overflows
}
}
如果您不想使用异常,那么可以使用旧的c函数std::strtol
:
std::string input;
if (std::getline(std::cin, input))
{
char* end = nullptr;
long n = std::strtol(input.c_str(), &end, 10);
if (n == LONG_MAX && errno == ERANGE)
{
// Input contains a number, but it's to big and owerflows
}
else if (end == input.c_str())
{
// Input not a number, treat as string
}
else if (end == input.c_str() + input.length())
{
// The input is a number
}
else
{
// Input begins with a number, but also contains some
// non-number characters
}
}
标准方法是提前1个字符查找
int nextInt()
{
std::stringstream s;
while (true)
{
int c = getch();
if (c == EOF) break;
putch(c); // remove if you don't want echo
if isDigit(c)
s << (char)c;
else if (s.str().length() > 0)
break;
}
int value;
s >> value;
return value;
}
您应该能够将此示例转换为对文件中的所有"words"重复此过程。
相关文章:
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- <string> 如何在使用 SWIG 时将 int 数组和 List 作为参数传递给 C# C++
- OpenCV undefined reference to 'cv::imread(cv::String const&, int)'
- map<string, int> m= {}; 在C++中是什么意思?
- 如何从map<pair<string,int>,pair<string,Array>>中迭代和查找?
- C++将文件行分离为String和Int
- 与 string.size() 比较时 int 的符号性显示警告
- freq_table[field_pm_value] = map<string, int>(); 是什么意思?
- 将 int 附加到 std::string
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 按值对 std::unordered_map<std:::string, std::atomic<unsigned int>> 进行排序
- 在 C++03 中将 std::string 转换为 int
- 方括号在"map <string, int> instance[numberFeatures];"中是什么意思
- 如何使用 c++ 中的 int* count(const string&s)计算字符串中每个数字的出现次数?
- 如果可以将其放在私有中,为什么要使用静态常量(int/string/.)?
- 在字节数组存储中嵌入 int/string
- c++中从double/int/string到bool的自动转换
- c++ string (int) + string (int)
- 如何在int,string类型的映射上使用find