stringstream peek() error C3867 - string

I have method of a class, that accepts a key variable and looks up the key in an underdone map. The Value is a string example: "12132, jack_arog, 1990:12:8:3:25:3"; method will use peek() in stringstream to recognize ',' and ' ' to ignore them and put the rest in a vector. Afterwards method will assign members of vector to attributes of an object.
Error is recieve during compilation:
if (ss.peek() == ',' || ss.peek == ' ')
ss.ignore();
Error C3867 'std::basic_istream<char,std::char_traits<char>>::peek': non-standard syntax; use '&' to create a pointer to member
I looked up this error and most say you forgot () when calling a function, however i do not believe this is my problem.
Method:
void Account::find_account(std::string name, std::string ID)
{
std::string key = name + "," + ID;
Account new_account;
std::unordered_map<std::string, std::string>::const_iterator got = map.find(key);
if (got == map.end())
std::cout << "not found";
else
{
std::string my_string = got->second;
std::vector<std::string> holder;
std::stringstream ss(my_string);
std::string i;
while (!my_string.empty() && ss >> i)
{
holder.push_back(i);
if (ss.peek() == ',' || ss.peek == ' ')
ss.ignore();
}
for (int i = 0; i < holder.size(); i++)
{
if (i = 0)
new_account.ID = holder.at(i);
if (i = 1)
new_account.account_holder = holder.at(i);
if (i = 2)
{
std::string::size_type sz;
new_account.amount_available = std::stof(holder.at(i), &sz);
}
if (i = 3)
{
new_account.date_created = holder.at(i);
}
}
}
}

"I looked up this error and most say you forgot () when calling a function, however i do not believe this is my problem."
How can you say that when your compiler tells you that the error is exactly on this line? Moreover it is telling you that the error is specifically tied to your (ab)use of peek, I quote:
"...peek': non-standard syntax; use '&' to create a pointer to member
I translate: The compiler thinks you are not trying to call peek, since you did not type the required () to do so. So, if you are by any chance trying to get the function address, you should prepend & to the function name for the syntax to be correct.
Computers are dumb, I'll give you that, but they are rarely wrong.

Related

How do i delete any item from a linked list?

I'm trying to write a function that deletes an element at a given position from a linked list, for now im using a linked list with only a head pointer. Now it may be that the user inputs a position that is larger than the size of the linked list so to remedy that i wrote this:
int delete(struct node** head, int pos)
{
struct node* temp = *head;
while(pos!=0 && temp->next!=NULL)
{
temp=temp->next;
pos--;
}
if(pos>0)
return 0;
}
but it gives the following error
fish: './a.out' terminated by signal SIGSEGV (Address boundary error)
i tried to debug it by writing a new code
int delete(struct node** head)
{
if((*head)->next==NULL)
return 1;
}
but it gives the same error
When head is NULL the evaluation of temp->next will give undefined behaviour or the error as you experienced.
However, there is more to correct to your function.
There is no deletion happening. To delete a node, its predecessor should have its next property update to point to the node after the removed node. The removed node should then be freed.
The value of *head should be modified when the first node of the list is removed.
The function should return an int, and so also when the deletion was successful (and pos == 0 after the loop), there should be a return that is executed, probably returning 1 to indicate success.
Not a problem, but I would advise using a different name for your function. If ever you move to C++, then delete will be a reserved word.
So:
int removeNode(struct node** head, int pos) {
if (*head == NULL) {
return 0;
}
struct node* temp = *head;
if (pos == 0) { // Case where first node must be removed
*head = (*head)->next; // Modify head reference
free(temp);
return 1; // Indicate success
}
while (pos > 1 && temp->next != NULL) {
temp = temp->next;
pos--;
}
if (pos != 1 || temp->next == NULL) {
return 0; // Invalid position
}
// Remove the node
struct node* prev = temp;
temp = temp->next;
prev->next = temp->next;
free(temp);
return 1; // Indicate success
}
as #paddy commented,
i didn't consider the case where head itself is pointing to NULL.
a simple if statement solved it
struct node* temp = *head;
if(temp==NULL){
printf("Empty LL\n");
free(temp);
return 0;
}

LLVM FunctionCall

I started working with LLVM recently and I have a problem with inserting a function in my IR Code.
At first my function was just like this:
print(){
printf("Hello")
}
And I managed to insert it before every CALL instruction with this code :
Function *fun;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
if (F->getName() == "print") {
fun= cast<Function>(F);
}
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
if (isa<CallInst>(&(*BI))) {
CallInst *CI = dyn_cast<CallInst>(BI);
Instruction *newInst = CallInst::Create(fun, "");
BB->getInstList().insert(BI, newInst);
}
}
}
Now I am trying to do this same thing (inserting my print function before every call instruction) but my print function must be this type of function :
void print (string something){
printf ("hello");
do something with "something" string but whatever;
}
I tried everything I found without success...
(I don't understand how is working IRBuiler, createGlobalString/Ptr, and getOrInsertFunction() and it must be my problem... Can Someone help me? Thank you...
The way to instrument such a function call is like
CallInst* callonFree = CallInst::Create(your_print_fun, {CI->getOperand(0)},"",CI);
Usually you can try to convert your string to a char*, which would be simpler to instrument.

Simple loop inside template -- variable 'x' cannot be read at compile time

(Note that I am extremely new to DLang (first day) so I am probably doing something very stupid)
I am trying to create a mixin template to re-use in my app's domain classes, which will automatically generate a toString1() method at compile-time, which will loop through the implementing struct's properties and generate code to print them.
To accomplish this, I am getting a const array of all of the struct's properties and trying to loop through them. However, when I try to access the index inside the loop (which should be perfectly executable at compile-time -- since we are looping against a known value) it fails.
It works completely fine if I use hard-coded indexes.
template Printable() {
import std.algorithm.iteration;
import std.conv;
import std.meta;
import std.stdio;
import std.format;
import std.range;
import std.typecons;
string toString1() const {
const auto traits = __traits(allMembers, typeof(this));
const auto internalWrap = (const string s) => "`" ~ s ~ ": ` ~ this." ~ s ~ " ~ `\n`";
const auto ret = iota(0, traits.length)
.map!((const int x) => traits[x]) // Error: variable x cannot be read at compile time
.fold((a, b) => a ~ b);
pragma(msg, internalWrap(traits[0])); // WORKS GREAT
return "";
}
}
(Just a note that I also tried doing it using both for-loops as well, but it fails with the same error).
I wanted to put an answer on this so this is a code example about what we went over in the comments:
struct A {
int a;
string b;
mixin Printable; // adds the toString1 method
}
mixin template Printable() {
string toString1() const {
string s;
import std.conv;
// loop over the trait directly, don't try to feed it
// through variables to ensure still available
foreach(memberName; __traits(allMembers, typeof(this))) {
// this ensures we are only actually trying to print actual fields
// (only fields have an offsetof property) since printing member
// variables will not be helpful
static if(is(typeof(__traits(getMember, this, memberName).offsetof))) {
if(s.length)
s ~= "\n";
// name
s ~= memberName;
s ~= " = ";
// value, converted to string
s ~= to!string(__traits(getMember, this, memberName));
}
}
return s;
}
}
void main() {
import std.stdio;
A a = A(14, "string");
writeln(a.toString1());
}
prints
a = 14
b = string

Comparing String.Index values

Is it possible to compare two String.Index values in Swift? I'm trying to process a string character by character, and several times I need to check if I am at the end of the string. I've tried just doing
while (currentIndex < string.endIndex) {
//do things...
currentIndex = currentIndex.successor()
}
Which complained about type conversions. Then, I tried defining and overload for < as such:
#infix func <(lhs: String.Index, rhs: String.Index) -> Bool {
var ret = true //what goes here?
return ret
}
Which gets rid of compilation errors, but I have no clue what to do in order to compare lhs and rhs properly. Is this the way I should go about using String.Index, or is there a better way to compare them?
The simplest option is the distance() function:
var string = "Hello World"
var currentIndex = string.startIndex
while (distance(currentIndex, string.endIndex) >= 0) {
println("currentIndex: \(currentIndex)")
currentIndex = currentIndex.successor()
}
Beware distance() has O(N) performance, so avoid it for large strings. However, the entire String class doesn't currently handle large strings anyway — you should probably switch to CFString if performance is critical.
Using an operator overload is a bad idea, but just as a learning exercise this is how you'd do it:
var string = "Hello World"
var currentIndex = string.startIndex
#infix func <(lhs: String.Index, rhs: String.Index) -> Bool {
return distance(lhs, rhs) > 0
}
while (currentIndex < string.endIndex) {
currentIndex = currentIndex.successor()
}
String indexes support = and !=. String indexes are an opaque type, not integers and can not be compared like integers.
Use: if (currentIndex != string.endIndex)
var currentIndex = string.startIndex
while (currentIndex != string.endIndex) {
println("currentIndex: \(currentIndex)")
currentIndex = currentIndex.successor()
}
I believe this REPL/Playground example should illuminate what you (and others) need to know about working with the String.Index concept.
// This will be our working example
let exampleString = "this is a string"
// And here we'll call successor a few times to get an index partway through the example
var someIndexInTheMiddle = exampleString.startIndex
for _ in 1...5 {
someIndexInTheMiddle = someIndexInTheMiddle.successor()
}
// And here we will iterate that string and detect when our current index is relative in one of three different possible ways to the character selected previously
println("\n\nsomeIndexInTheMiddle = \(exampleString[someIndexInTheMiddle])")
for var index: String.Index = exampleString.startIndex; index != exampleString.endIndex; index = index.successor() {
println(" - \(exampleString[index])")
if index != exampleString.startIndex && index.predecessor() == someIndexInTheMiddle {
println("current character comes after someIndexInTheMiddle")
} else if index == someIndexInTheMiddle {
println("current character is the one indicated by someIndexInTheMiddle")
} else if index != exampleString.endIndex && index.successor() == someIndexInTheMiddle {
println("Current character comes before someIndexinTheMiddle")
}
}
Hopefully that provides the necessary information.
Whatever way you decide to iterator over a String, you will immediately want to capture the iteration in a function that can be repeatedly invoked while using a closure applied to each string character. As in:
extension String {
func each (f: (Character) -> Void) {
for var index = self.startIndex;
index < self.endIndex;
index = index.successor() {
f (string[index])
}
}
}
Apple already provides these for C-Strings and will for general strings as soon as they get character access solidified.

Using an array as a parameter in Haxe

I have a function that takes an array as a parameter, and it keeps returning the following error message:
Test.hx:34: characters 23-24 : Array<Int> should be { length : Void -> Int }
Test.hx:34: characters 23-24 : Invalid type for field length :
Test.hx:34: characters 23-24 : Int should be Void -> Int
Test.hx:34: characters 23-24 : For function argument 'array'
This is the code that produced the error message:
class Test{
static function main() {
var a = new Array();
a = [1,2,3,4];
enlarge1DArray(a); //why won't it work when I try to invoke this function?
}
static function enlarge1DArray(array){
var i = 0;
while(i < array.length()){
i++;
trace("i is " + i);
}
}
}
The length you are trying to access is a property, not a method. See the Array API Documentation.
Change the while line from this:
while(i < array.length())
to this:
while(i < array.length)
Detailed Answer:
The error you're getting is due to Haxe getting confused as it's guessing at the types. Basically, because you had were treating length as a method, it was assuming that the array parameter in the enlarge1DArray had to be some kind of object that had a method called length, with the type signature "Void->Int".
In short, because you were asking for a method, it was expecting the parameter "array" to have:
{ length : Void -> Int }
when an Array actually has:
{ length : Int }
So the compiler got confused and said you had your typing wrong. You can read more about this on the Haxe wiki page for Type Inference. In future you can explicitly state what the types of each function parameter are, and then Haxe will give you more useful error messages.

Resources