检查c ++中字符串中字符的值

时间:2016-10-04 15:22:36

标签: c++

我正在编写一个用c ++读取和写入.txt文件的程序。以下是我的代码的部分编辑样本:

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <windows.h>
#include <sstream>
#include <algorithm>

//functions
template <typename T>
string num_to_string(T pNumber)
{
     ostringstream oOStrStream;
     oOStrStream << pNumber;
     return oOStrStream.str();
}
bool isdot(const char &c)
{
     return '.'==c;
}
//needed for string_to_num()

float string_to_num(string s)
{
     s.erase(remove_if(s.begin(), s.end(), &isdot ),s.end());
     replace(s.begin(), s.end(), ',', '.');
     stringstream ss(s);
     float v = 0;
     ss >> v;
     return v;
}

//code

string line = 10/20;
//the line taken from the .txt file
float add_numerator = 5;
float add_denominator = 10;
//these are values just for example

for(int i = 0; i < line.size(); i+= 1) {
     if (numerator_finished == false){
          if (line[i] != "/"){
               numerator += line[i];
          }else {
               numerator_finished = true;
          }
     }else {
          denominator += line[i];
     }
}
float numerator_temp = string_to_num(numerator);
float denominator_temp = string_to_num(denominator);
numerator_temp += add_numerator;
denominator_temp += add_denomitator;

numerator = num_to_string(numerator_temp);
denominator = num_to_string(denominator_temp);

string add_string = numerator + "/" + denominator;
//add_string is what the line in the .txt file is changed to with not shown code

如果运行此代码,则应该是add_string =&#34; 15/30&#34;。但由于这一行,它无法编译:

if (line[i] != "/"){

由于此行,会出现此错误:
&#34; ISO C ++禁止在指针和整数[-fpermissive]&#34;

之间进行比较

我不明白当它们都是字符串时这是一个指针和整数。

是否可以解释此错误并显示修复?

1 个答案:

答案 0 :(得分:0)

  

我不明白当它们都是字符串时这是一个指针和整数。

他们这两个字符串! line是一个字符串,但line[i]char

"/"是一个字符数组(字符串文字)。

使用'/'来获取字符文字,与char进行比较非常好。